Division by zero error after incorrect sql query

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
robster
Forum Contributor
Posts: 360
Joined: Wed Jul 16, 2003 8:28 am
Location: Sunshine Coast, Australia

Division by zero error after incorrect sql query

Post 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
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post 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;
User avatar
robster
Forum Contributor
Posts: 360
Joined: Wed Jul 16, 2003 8:28 am
Location: Sunshine Coast, Australia

Post by robster »

thanks so much, seems so obvious now...

:)

Rob
Post Reply