note 101655 deleted from function.mysql-query by philip
| From: | philip@php.net | Date: | Sun, 10 Jul 2011 22:25:54 +0000 |
| Subject: | note 101655 deleted from function.mysql-query by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-181409@lists.php.net to get a copy of this message | ||
Note Submitter: jack dot thomson at bgmc dot ca
----
Here is something I use all the time. It save on typing and adding extra if..else blocks to my
code. Basically, you use the function in a specific if statement to determine if there are any
records in your table, and if there are continue with a mysql_fetch_array loop.
Common usage:
<?php
if (get("select * from contacts where verified='on'", $q_contact) > 0)
{
while ($r_contact = mysql_fetch_array($q_contact))
{
// commands to apply to each record
}
} else {
// There are no records that match
}
?>
The "$q_contact" is passed by reference, so that any results of the query are put into it
via mysql_query. The function itself returns the number of rows that are returned. If there is a
mysql_error, -1 is returned.
<?php
// This function returns the number of rows returned in the SQL query, and assigns the results array
to the array provided
// Returns -1 if there is an error and prints the error
function get($sql, &$array)
{
$array = "";
$q = mysql_query($sql);
if (mysql_error())
{
$ret = -1;
print "<div><font style='font-family: arial; font-size: 12px;'><font
style='color: red;'>Error:</font> " . mysql_error() .
"</font></div>";
exit(1);
} else {
$ret = mysql_num_rows($q);
if ($ret > 0)
{
$array = $q;
}
}
return $ret;
}
?>