Page 1 of 1
Error with the following code
Posted: Tue Apr 26, 2011 8:34 pm
by achilles1971
[text]
This seems like it should be simple...but for the life of me, I can't find the problem.
I have the following code:
176 <?php
177
178 $result=mysql_query("SELECT * FROM `olivia` ORDER BY `id` ASC");
179
180 while($row = mysql_fetch_array($result)){
181 echo "<b>" . $row[`quote`] . "</b><br /><br />";
182 }
183
184 ?>
And I get the following error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\olivia\index.php on line 181
Can someone help me figure this out?
[/text]
Re: Error with the following code
Posted: Wed Apr 27, 2011 2:03 am
by andym01480
Code: Select all
$sql="SELECT * FROM `olivia` ORDER BY `id` ASC";
echo $sql;//just checking!
$result=mysql_query($sql) OR die (mysql_error());// the die may give some clues!
//...
Re: Error with the following code
Posted: Wed Apr 27, 2011 6:22 am
by achilles1971
This seems to work:
Code: Select all
<?php
$result="SELECT * FROM `quotes` ORDER BY `id` ASC";
$query = mysql_query($result) OR die (mysql_error());
while($row = mysql_fetch_array($query)){
echo "<b>" . $row['quote'] . "</b><br /><br />";
}
?>
Thanks.
Re: Error with the following code
Posted: Wed Apr 27, 2011 6:45 am
by andym01480
Great, glad it works! - but by your response, it looks like you are not that clear on what sql statements do. Your first post was trying to select all the rows from a database table called `olivia` in ascending order of id- but the table `olivia` (or the field `id`) doesn't exist. The table `quotes` does, so now your code works.
But in a few days, weeks, or months the way you have written your second post code will confuse you or anyone else checking your code.
mysql_query provides a "result" for a "query" you give it. So a more legible, understandable way to write it would be
Code: Select all
$query = "SELECT * FROM `quotes` ORDER BY `id` ASC";
$result = mysql_query($query) OR die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<b>" . $row['quote'] . "</b><br /><br />";
}
Also as you are only using the field `quote` from the table `quotes`, you could optimise the query (especially if it will be a large table), by just grabbing that
Code: Select all
$query="SELECT `quote` FROM `quotes` ORDER BY `id` ASC";
Re: Error with the following code
Posted: Wed Apr 27, 2011 7:59 am
by prensil
You need to check the $row exist before use it in echo statement?
Re: Error with the following code
Posted: Wed Apr 27, 2011 8:16 am
by andym01480
Prensil - The echo in the while loop only happens when a row can be fetched from the result. If achilles1971 uses SELECT `quote` then he won't need to check!