PHP send quesries to mySQL using mysql_query
function. mysql_query function returns boolean (True or False) value
which your quesry does not return any records.If query is true,
returning value must pass to mysql_fetch_array().
Sending queries to mySQL
PHP send quesries to mySQL using mysql_query
function. mysql_query function returns boolean (True or False) value
which your quesry does not return any records. Queries (sql statements)
like SELECT, SHOW, DESCRIBE, EXPLAIN return false value on error. If
query is true, returning value must pass to mysql_fetch_array().
Let's see it in action. We have used a common database to query some
fields from mySQL database. Code is complete, but need to update
connection string.
mysql_connect("localhost","root",""); //(mysql server, username, password)
mysql_select_db("shop") or die("Can not find database");
$query="select * from products";
$result=mysql_query($query);
while($row=mysql_fetch_row($result))
{
echo $row[1] . '- ' . $row[2] . '
';
}
?>
Error handling:
If you want to catch error in an SQL statement, need to add
mysql_error() in your code. That's simple. Now test it in our code. Our
sql statement is wrong, turns false.
mysql_connect("localhost","root",""); //(mysql server, username, password)
mysql_select_db("shop") or die("Can not find database");
$query="select * from productsss";
$result=mysql_query($query);
if (!$result)
{
die('Query returned false;
error message:' . mysql_error());
}
else
{
while($row=mysql_fetch_row($result))
{
echo $row[1] . '- ' . $row[2] . '
';
}
}
?>
We have placed our error message and mysql error message together.
But first we need to check that mysql_query is returning a boolean
value. If turning value is false, we will not pass retuning value to
mysql_fetch_row;
I think this simple code will be helpfull for you.
|