Jump to content

Dividing by ZERO!


3p1demicz

Recommended Posts

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 :)

 

Link to comment
https://forums.phpfreaks.com/topic/296926-dividing-by-zero/
Share on other sites

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?

Link to comment
https://forums.phpfreaks.com/topic/296926-dividing-by-zero/#findComment-1514394
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/296926-dividing-by-zero/#findComment-1514395
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.