Jump to content

Dividing by ZERO!


3p1demicz
Go to solution Solved by Barand,

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
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
Share on other sites

  • Solution

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.