Faheem Ali
Faheem Ali

Reputation: 21

Retrieve Data From DB using PHP

I created a database (table) in SQL similar to this.

   x   y   z
1  x1  y1  z1
2  x2  y2  z2

This is a table that I created; now I want to do some math on it using PHP. How can I retrieve the data and perform math on it? How to get data from the DB table and save them in PHP variables?

function ans($x1, $y2, $z2)
{
#a = x1 - y2;
#z2 = $z2 -$a;
}

Upvotes: 0

Views: 199

Answers (2)

e03050
e03050

Reputation: 1582

mysql_connect is going to be deprecate. http://php.net/manual/en/function.mysql-connect.php

use mysqli instead http://www.php.net/manual/en/book.mysqli.php

Upvotes: 0

Conrad Lotz
Conrad Lotz

Reputation: 8838

The code will look as follow:

<?php

 $con = mysql_connect("localhost","username","password");
 if (!$con)
   {
   die('Could not connect: ' . mysql_error());
   }

mysql_select_db("database", $con);

$xAnswer = 0;
$yAnswer = 0;
$zAnswer = 0;

$result = mysql_query("SELECT x,y,z FROM MathTable");

while($row = mysql_fetch_array($result))
   {
     $xAnswer = Add($row["x"],$row["y"]);
     $yAnswer = Multiply($row["z"],$row["y"]);
     $zAnswer = Subtract($row["z"],$row["x"]);
   }

mysql_close($con);


    function Add($x,$y)
    {
       return $x + $y;
    }

    function Subtract($x,$y)
    {
       return $x-$y;
    }

    function Multiply($x,$y)
    {
       return $x*$y;
    }

    function Divide($x,$y)
    {
       return $x/$y;
        }
 ?>

Alternatively one can handle the math in the sql as well as follow and then just pull the answers into a variable:

SELECT (x+y) AS Add,(x-y) AS Subtract,(z/x) AS Divide FROM MathTable

The the loop through the recordsset will be as follow

while($row = mysql_fetch_array($result))
       {
         $xAnswer = $row["Add"];
         $yAnswer = $row["Subtract"];
         $zAnswer = $row["Divide "];
       }

Remember that the variables will have a different answer everytime the loop increments because of the amount of records in the table so you might want a running total or alternatively you can keep running total inside using the above Add example variables:

$xAnswer = $xAnswer  + $row["Add"];

Upvotes: 1

Related Questions