PDA

View Full Version : How do I avoid division by zero error?

mouse
Jul 20th, 2002, 11:47 PM
Warning: Division by zero in...

I'm trying to calculate a percentage using...

\$percent1 = round((\$num_rows1*100)/\$num_rows_total);

\$percent2 = round((\$num_rows2*100)/\$num_rows_total);

and so on...

what's causing this error and what can I do to prevent it?

Spookster
Jul 20th, 2002, 11:56 PM
Well that's easy.....stop dividing by zero. :D

Ok well if your num_rows_total variable is equal to zero then obviously you will get this error. Are these rows referring to records in a database?

You could put a conditional statement in there:

if(\$num_rows_total!=0)
\$percent1 = round((\$num_rows1*100)/\$num_rows_total);
\$percent2 = round((\$num_rows2*100)/\$num_rows_total);
}
else{
//do something else if it is zero
}

mouse
Jul 21st, 2002, 12:06 AM
Hold on! :confused:

There's got to be rows in order to call this expression so I should never see this error :confused:

....

okay I've sorted it simply by moving the bit that counts total rows ahead of the bit using the resulting variable, so now I'm thinking php works down the page? :o:rolleyes:

Thatks for the quick response anyhoo :thumbsup:

Spookster
Jul 21st, 2002, 01:23 AM
just like any language the coding will be read left to right and top to bottom unless unless you put coding into functions/methods/subroutines etc. :)

foxy
Apr 14th, 2006, 07:11 AM
Glad to find this post and I hope you can assist me.

I'm building an application where the a row I return many times may be 0.

\$query = mysql_query("SELECT * FROM Azgalor_Alliance WHERE \$metode LIKE '%\$search%' LIMIT 0, 50");
while (\$row = @mysql_fetch_array(\$query))
{
\$variable1=\$row["Item_Desc"];
\$variable2=\$row["Enchant"];
\$variable3=\$row["Item_Class"];
\$variable4=\$row["Min_Price"];
\$variable5=\$row["Total_Price"];

how can I go about making \$variable6 = 1 if it returns 0 ?

(this is for an auction system, Total_Price is the sum of all buy ammounts of an item and Buy_Count is the number of times the item has been purchased on the auction)

I figured an if statement would work... but I'm lost on how I should write it.:confused:

foxy
Apr 14th, 2006, 07:21 AM
if ( \$variable6 == 0) {
\$variable6 = 1;
} else {
}

nithin.sha
Oct 2nd, 2008, 12:56 PM
this is the code showing error

Pasting a part of it

<?php

\$result = mysql_query("SELECT * FROM news where section = 'news' ORDER BY id DESC LIMIT 0 , 4 ");

\$i = 0;

\$news_id = array();
//(Line 103 Comes here )
\$news_title = array();

\$news_content = array();

while(\$row = mysql_fetch_array(\$result))

{

\$news_id[\$i] = \$row['id'];

\$news_title[\$i] = \$row['title'];

\$news_content[\$i] = \$row['content'];

\$i++;

}

masterofollies
Oct 2nd, 2008, 03:44 PM
Yes your database has 0, so it's trying to times a number that can't be times.

nithin.sha
Oct 3rd, 2008, 10:50 AM
Yes your database has 0, so it's trying to times a number that can't be times.

How Can I solve it sir