Page 1 of 1

Division by zero error after incorrect sql query

Posted: Sat Nov 12, 2005 8:03 pm
by robster
Hi all,

I am doing something like this:

Code: Select all

function report_daily_products_info($date_to_report)
	{
		$short_date = extract_date_only($date_to_report);

		global $dbname;
		mysql_select_db($dbname);
		$sql = "SELECT * FROM transactions WHERE date = '$short_date' && type = 'stock' ORDER BY id ASC";
	    $content = mysql_query($sql);
		$Xcontent = mysql_fetch_array($content);	  
		$num_rows = mysql_num_rows($content);
...
..
..etc etc
which is fine until it is called and there is no transaction where date = $date_to_report (or $short_date). What I get then is a:

Code: Select all

Warning: Division by zero in location\of\site\functions_reports.php on line 138
How can I do a check before calling this function? I am currently calling it like so:

Code: Select all

$report_daily_products_info_array = report_daily_products_info($date_to_report);
$date_to_report is a date selected by the user. As I say, when the sql tries to pull a transaction from the database, it all works well, really well, but if there is no transaction on that date, then I get the error. I want to be able to say, draw the results if there are results, or if there aren't, then don't draw them and don't show an error ;)

I'm sort of stuck on this.... any help would be greatly appreciated. :)


Rob

Posted: Sat Nov 12, 2005 11:17 pm
by RobertGonzalez
EDIT: Wanted to make it relevent to your example

After you set your result variable to the mysql_query() function return value run mysql_num_rows() on it and compare the value to greater than zero. If it is, run your computation, if it is not, do what happens when there is a zero.

Like this...

Code: Select all

$num_rows = mysql_num_rows($content);
if ($num_rows > 0)
{
    //Run the computation
    //Return the completed value
}

return false;

Posted: Sun Nov 13, 2005 12:44 am
by robster
thanks so much, seems so obvious now...

:)

Rob