2015-04-12 108 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

相關問題