2015-04-12 172 views
0

我有一个脚本来从数据库中获取信息,并使用while循环来检查它是否符合某些条件。第一个条件总是满足,但第二个条件不满足。
这里是我使用的代码:While循环不满足这两个条件

//Get the new ad's id 
    $stmt = mysqli_prepare($db, "SELECT visits, description, url, views, time FROM paidAds WHERE id=? AND finished!=?"); 
    //Bind Items 
    mysqli_stmt_bind_param($stmt, 'ii', $currentAd, $adFinished); 
    //Execute statement 
    mysqli_stmt_execute($stmt); 
    //Bind password to variable 
    mysqli_stmt_bind_result($stmt, $adVisits, $adDescription, $adUrl, $adViews, $adTime); 
    //Fetch password 
    mysqli_stmt_fetch($stmt); 
    //Close statement 
    mysqli_stmt_close($stmt); 

    //Get the new ad's id 
    $stmt2 = mysqli_prepare($db, "SELECT ip FROM adViews WHERE adId=? AND address=?"); 
    //Bind Items 
    mysqli_stmt_bind_param($stmt2, 'is', $currentAd, $address); 
    //Execute statement 
    mysqli_stmt_execute($stmt2); 
    //Bind password to variable 
    mysqli_stmt_bind_result($stmt2, $userIp); 
    //Fetch password 
    mysqli_stmt_fetch($stmt2); 
    //Close statement 
    mysqli_stmt_close($stmt2); 

    if($stmt2 === false){ 
     echo mysqli_error($db); 
    } 

    while($adDescription == '' && $userIp != ''){ 
     $currentAd += 1; 

     //Get the new ad's id 
     $stmt = mysqli_prepare($db, "SELECT visits, description, url, views, time FROM paidAds WHERE id=? AND finished!=?"); 
     //Bind Items 
     mysqli_stmt_bind_param($stmt, 'ii', $currentAd, $adFinished); 
     //Execute statement 
     mysqli_stmt_execute($stmt); 
     //Bind password to variable 
     mysqli_stmt_bind_result($stmt, $adVisits, $adDescription, $adUrl, $adViews, $adTime); 
     //Fetch password 
     mysqli_stmt_fetch($stmt); 
     //Close statement 
     mysqli_stmt_close($stmt); 

     //Get the new ad's id 
     $stmt2 = mysqli_prepare($db, "SELECT ip FROM adViews WHERE adId=? AND address=?"); 
     //Bind Items 
     mysqli_stmt_bind_param($stmt2, 'is', $currentAd, $address); 
     //Execute statement 
     mysqli_stmt_execute($stmt2); 
     //Bind password to variable 
     mysqli_stmt_bind_result($stmt2, $userIp); 
     //Fetch password 
     mysqli_stmt_fetch($stmt2); 
     //Close statement 
     mysqli_stmt_close($stmt2); 

     if($userIp != ''){ 
      echo 'error'; 
     } 
    } 

    echo $userIp; 

这个脚本的输出不显示任何“错误的,因为它应该,但打印变量$ USERIP当它是不是空的。
这是为什么?

+0

为什么你要在循环内进行循环之前做同样的查询?必须有一个'JOIN'查询,你可以这样做,以防止你正在尝试的4个查询。 – Sean

+0

第一个查询是获取循环中要检查的初始变量。我会研究JOIN查询,谢谢。 – Minifrij

回答

0

我想这是因为你使用

mysqli_stmt_bind_result($stmt, $adVisits, $adDescription, $adUrl, $adViews, $adTime); 

程序已进入while循环之前。所以$ adDescription!='',程序不会进入循环。

+0

我不能说我很确定你的意思。你能否给出一个事例应该进入的榜样? – Minifrij

+0

您正在为$ adDescription赋值,所以它不是=='',程序将不会进入while循环。我认为你应该试着去掉$ adDescription ==''作为while循环的条件,因为我实际上并不知道这种情况的原因。 – jkhsjdhjs

+0

如果数据库中“已完成”列等于1,$ adDescription的第一个值可能为空。如果$ adDescription的值不为空,while循环不会运行,尽管不满足第二个条件? – Minifrij

相关问题