hatched
hatched

Reputation: 865

PHP - How do I run mysql query in while loop?

My original query was to select data from phpadmin table and display into table.

$sql="select * from table";
$result=mysql_query($sql) or die(mysql_error());

while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
{
    extract($myrow);
    echo "<td align='left' bgcolor='$bgclr'>".$myrow[0]."</td>";    
    echo "<td align='left' bgcolor='$bgclr'>".$myrow[1]."</td>";    
    echo "<td align='left' bgcolor='$bgclr'>".$myrow[2]."</td>";    
    echo "<td align='left' bgcolor='$bgclr'>".$myrow[3]."</td>";    
}


Then I need to display another column using value of $myrow[0] to execute another query to get the value.

$sql="select * from table";
$result=mysql_query($sql) or die(mysql_error());

while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
{
    extract($myrow);

    $id = $myrow[0];
    $sql="select amount from table2 where id like '%$id%'";
    $result = mysqli_query($conn, $sql);

    echo "<td align='left' bgcolor='$bgclr'>".$myrow[0]."</td>";    
    echo "<td align='left' bgcolor='$bgclr'>".$myrow[1]."</td>";    
    echo "<td align='left' bgcolor='$bgclr'>".$myrow[2]."</td>";    
    echo "<td align='left' bgcolor='$bgclr'>".$myrow[3]."</td>";    

    while ($row=mysqli_fetch_row($result)) {

            echo "<td align='left' bgcolor='$bgclr'>".$row[0]."</td>";echo "</tr>";
        }   
    }


And my page became blank. And the error was at

$result = mysqli_query($conn, $sql);

Is it the correct method or how should I do it?

Upvotes: 0

Views: 5440

Answers (1)

Lovepreet Singh
Lovepreet Singh

Reputation: 4860

You overwrite variable $result while executing query inside the loop here:

$sql="select amount from table2 where id like '%$id%'";
$result = mysqli_query($conn, $sql);

Change variable name $result inside the loop and code will be like:

$sql="select amount from table2 where id like '%$id%'";
$result2 = mysqli_query($conn, $sql);

Also update it here:

while ($row=mysqli_fetch_row($result2)) {

            echo "<td align='left' bgcolor='$bgclr'>".$row[0]."</td>";echo "</tr>";
        }   
    }

Upvotes: 3

Related Questions