Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop not printing all answers

Tags:

php

mysql

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?

P.S: My bad, $sql is being repeated, that was a silly mistake

like image 541
Namit Avatar asked Mar 10 '26 13:03

Namit


1 Answers

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 ?

like image 181
Manse Avatar answered Mar 12 '26 03:03

Manse