3p1demicz Posted June 19, 2015 Share Posted June 19, 2015 Dear people, I have a problem for solving. I have numbers in my database saved with decimal atribute. The numbers go below zero like this '0.55' and also above zero. I' m just testing my code and i came to this Dividing by zero problem. I need to do simple devision $variable / $ variable to get a needed number for my operation, but it just does not work ... help me pls. If i do it manually it works for ex. 0.55/ 0.2 = 2.75. I need to get this same output from my variables. I do much appriciate any hints where to fix this Quote Link to comment https://forums.phpfreaks.com/topic/296926-dividing-by-zero/ Share on other sites More sharing options...
cyberRobot Posted June 19, 2015 Share Posted June 19, 2015 Before performing the operation, you could run an if test to make sure the divisor isn't zero. Quote Link to comment https://forums.phpfreaks.com/topic/296926-dividing-by-zero/#findComment-1514387 Share on other sites More sharing options...
3p1demicz Posted June 19, 2015 Author Share Posted June 19, 2015 here is the code. <?php $request = mysql_query("SELECT * FROM database WHERE ean = '12' ") or die (mysql_error()); $calculation1 = ($price / $weight); while ($row = mysql_fetch_array($request)) { echo "$row[name] and $row[weight]<br>"; echo "$row[price] and $calculation1 <br>"; echo "<br><br>"; } Can you explain more? I have the calculation after selecting data from the database. Should i put the if statment before the while, is that what you suggest? Quote Link to comment https://forums.phpfreaks.com/topic/296926-dividing-by-zero/#findComment-1514394 Share on other sites More sharing options...
Solution Barand Posted June 19, 2015 Solution Share Posted June 19, 2015 The calculation in that position does nothing - $price and $weight have not been defined. $request = mysql_query("SELECT * FROM database WHERE ean = '12' ") or die (mysql_error()); while ($row = mysql_fetch_array($request)) { if ($row['weight']==0) { $calculation1 = 0; } else { $calculation1 = $row['price'] / $row['weight']; } echo "$row[name] and $row[weight]<br>"; echo "$row[price] and $calculation1 <br>"; echo "<br><br>"; } Alternatively SELECT name , price , weight , CASE weight WHEN 0 THEN 0 ELSE price/weight END as calculation FROM database WHERE ean = '12' You should move off mysql_ functions and change to mysqli_ or PDO libraries instead. Quote Link to comment https://forums.phpfreaks.com/topic/296926-dividing-by-zero/#findComment-1514395 Share on other sites More sharing options...
3p1demicz Posted June 20, 2015 Author Share Posted June 20, 2015 Thank you very much!! it made my day Quote Link to comment https://forums.phpfreaks.com/topic/296926-dividing-by-zero/#findComment-1514407 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.