PHP while循环问题不会覆盖变量

时间:2014-09-03 18:41:02

标签: php mysql

我有这个while循环代码下面写的php,我不知道为什么循环不断重复所以我把一个计数器打破它。

在调试echo的结果时,似乎我的变量$ loop_userid不会覆盖。

Referral is 1021 Referral is 1021 Referral is 1021 Referral is 1021 Referral is 1021 Referral is 1021

我有一个sql记录列表。对于帐户1021,推荐是1000

这个想法是

3 Accounts

1008 > 1021 > 1000

But my loop stuck at 1021

我想知道为什么我的$ loop_userid不会覆盖从数据库中提取的新值。

从mysql数据库中选择

account_id  referral

1000
1008        1021
1021        1000

如果我回应我的sql select语句

select * from account where account_id='1008'
select * from account where account_id='1021'
select * from account where account_id='1021'
select * from account where account_id='1021'
select * from account where account_id='1021'
select * from account where account_id='1021'

以下是我的代码

$payment_owe_loop = "inside";
//initial userid is my own userid
$loop_userid = $UserId;

//此时UserId为1008

while($payment_owe_loop=="inside")
{

$sql_select = "select * from account where account_id='$loop_userid'";
$result = mysql_query($query);

//echo $sql_select;

$loop_userid = "";
$count = mysql_num_rows($result);

if($count>0)
{
while($rowINNER = mysql_fetch_array($result))
{
$loop_userid = $rowINNER['referral'];
$my_rebate = $rowINNER['rebate'];
$my_cost = (100 - $my_rebate) * $total_cost * 0.01;
}//end while fetch inner row
}//if there rows return

echo " Referral is " . $loop_userid;

if($count==0)
{
$payment_owe_loop = "outside";
}

if($counter>4)
{
$payment_owe_loop = "outside";
}

$counter++;

unset($rowINNER);

}//end while payment loop

问题解决。我发现我查询了错误的sql语句

$sql_select = "select * from account where account_id='$loop_userid'";
$result = mysql_query($query);

假设是$ sql_select而不是$ query

在sql语句中盲目,我错过了检查错误键入的变量

1 个答案:

答案 0 :(得分:3)

我唯一可以理解的是,由于您的account数据库使用account_id的字符串,因此某些account_id具有尾随空格。因此,您获得1008的推荐,即1021,但我不确定1021是否在数据库中,可能输入为“1021”(某些尾随空格)

我很想知道你的数据库直接在你的数据库上获得了什么(只是通过mysql客户端直接进行)

select * from account where account_id='1021';

这实际上是否会返回一行?如果没有,那么我怀疑是否需要修剪尾随空格。如果他们需要修剪,那么这行代码可能需要修改:

$sql_select = "select * from account where account_id='$loop_userid'";

为:

$sql_select = "select * from account where TRIM(account_id)='$loop_userid'";

旁注:虽然我确定这与您的问题无关,但我会考虑修改此代码:

if($count>0)
{
    while($rowINNER = mysql_fetch_array($result))
    {
        $loop_userid = $rowINNER['referral'];
        $my_rebate = $rowINNER['rebate'];
        $my_cost = (100 - $my_rebate) * $total_cost * 0.01;
    }//end while fetch inner row
}//if there rows return

至少改为:

if($count>0)
{
    rowINNER = mysql_fetch_array($result)
    $loop_userid = $rowINNER['referral'];
    $my_rebate = $rowINNER['rebate'];
    $my_cost = (100 - $my_rebate) * $total_cost * 0.01;
}//if there rows return

我假设account.account_id是一个唯一的密钥,你不能有超过1条记录。 $count 0 (没有此类account_id)或 1 。如果你有重复的account_id,那么这将导致灾难性的问题。