Php / Mysql While循环错误

时间:2011-03-02 19:50:56

标签: php

好的,我没有使用过这些回复,但我自己修复过。

我虽然总结了书籍的所有价格但我遇到了麻烦:

代码:

<style type="text/css">
table{font-size:1.11em;}
tr{background-color:#eee; border-top:1px solid #333;}
</style>
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("bookorama", $con);

$sql="SELECT customers.name, books.title, books.isbn, books.price 
         FROM customers, orders, order_items, books
         WHERE customers.customerID = orders.customerID 
         AND orders.orderID = order_items.orderID 
         AND order_items.isbn = books.isbn;";

$result = mysql_query($sql);     // You actually have to execute the $sql with mysql_query();
if($result === FALSE) {
    die(mysql_error()); // TODO: better error handling
}
echo "<h1 style='color:#3366ff;'>Each customer book orders</h1>";
echo "<table>";  //start the table

while($row = mysql_fetch_array($result, MYSQL_ASSOC))  //Loop through the results
{
    //echo each row of the table
    echo "<tr>";              
    echo "<th><strong>Customer Name:</strong><br></th>";               
    echo "<td>$row[name]</td>";       
    echo "<th><strong>Book Title</strong><br></th>";                
    echo "<td>$row[title]</td>";
    echo "<th><strong>ISBN</strong><br></th>";  
    echo "<td>$row[isbn]</td>";
    echo "<th><strong>Book Price</strong><br></th>";  
    echo "<td>$row[price]</td>";
    echo "</tr>";
} 

echo '</table>';   //close out the table

?>

3 个答案:

答案 0 :(得分:1)

mysql_query returns FALSE发生错误,您在尝试将其传递给mysql_fetch_array之前未检查此内容。

你真的应该在你的代码中加入错误检查!

答案 1 :(得分:0)

也许$ result因错误而包含false,请在mysql_query调用后添加此块。

if (!$result) {
    die('Invalid query: ' . mysql_error());
}

答案 2 :(得分:0)

因为您的来电$result = mysql_query($sql);有错误并返回false。在尝试使用资源之前,您需要检查错误:

$result = mysql_query($sql); 
if( !$result ) {
    echo "SQL Query failed! " . mysql_error();
}
else {
    // rest of your code here
}