简体   繁体   中英

While loop not printing all answers

This might be really simple, but i cannot figure out the problem with this code:

$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
    if(mysql_num_rows($sql) == 0) {
        echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
    }else {
        while($row = mysql_fetch_array($sql)) {
            echo mysql_num_rows($sql);
            echo 'reached';
            $book_id = $row[1];
            $sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
            echo "<tr><td>".$sql[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
        }
    }

Now based on my database the query is returning 2 results, the echo mysql_num_rows($sql) also gives out 2 . However the reached is echoed only once. Does anyone see a potential problem with the code?

PS: My bad, $sql is being repeated, that was a silly mistake

It will only echo once because of this line :

$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));

your overwriting the $sql variable.

Why not just run a single query and join the data you require ?

try ( $sql2 instead of $sql and $sql[0] to $sql2[0] ):

$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
    if(mysql_num_rows($sql) == 0) {
        echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
    }else {
        while($row = mysql_fetch_array($sql)) {
            echo mysql_num_rows($sql);
            echo 'reached';
            $book_id = $row[1];
            $sql2 = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
            echo "<tr><td>".$sql2[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
        }
    }

I think it'll be because you are ressetting the sql variable

            $sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));

when you are still using it in the while loop. :P

It's probably this line:

 $sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));

Try using a different variable name.

您正在更改循环内的$ sql变量,因此下次运行$ row = mysql_fetch_array($ sql)时,该值将不同(可能不会基于您的代码)。

Inside the while loop you are re-using the same variable: $sql . This is used to control the terminating condition of the loop.

Using a different variable name, eg $sql2 should leave the original variable intact and the loop should proceed as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM