Jump to content

PHP noob!!! mysql_fetch_row


superblunt

Recommended Posts

Hi I would like to do this but in more of a loop style

 

<?php

$con = mysql_connect("localhost","root","*****");

if (!$con)

  {

          die('Could not connect: ' . mysql_error());

    }

 

$db = mysql_select_db("testpos",$con);

$sql = "SELECT id FROM sales";

$result = mysql_query($sql,$con);

 

$row1 = mysql_fetch_row($result);  //row1 is 6

$row2 = mysql_fetch_row($result);  //row2 is 7

 

$rowmerge = array_merge($row1,$row2);

$sum = array_sum($rowmerge);

 

echo $sum;  // I get a total of 13

?>

 

If i use while to get the rows i get 2 arrays one with the 6 and one with the 7 but i dont know how to merge them.

 

<?php

$con = mysql_connect("localhost","root","*****");

if (!$con)

  {

          die('Could not connect: ' . mysql_error());

    }

 

$db = mysql_select_db("testpos",$con);

$sql = "SELECT id FROM sales";

$result = mysql_query($sql,$con);

 

 

while($row = mysql_fetch_row($result))

          {

            print_r($row); // the result is Array ( [0] => 6 ) Array ( [0] => 7 )

          }

?>

 

 

so how can i merge all the rows into one array so i can get a array_sum or is there any easier way to add the values of each array into a total sum

 

Thx for the help in advance

 

Link to comment
https://forums.phpfreaks.com/topic/111119-php-noob-mysql_fetch_row/
Share on other sites

<?php
$con = mysql_connect("localhost","root","*****")
  or die('Could not connect: ' . mysql_error());
$db = mysql_select_db("testpos",$con);

$sql = "SELECT id FROM sales";
$result = mysql_query($sql,$con);

$rowmerge = array();
while($row = mysql_fetch_row($result)) {
  $rowmerge[] = $row[0];
}
$sum = array_sum($rowmerge);
echo $sum;
?>

by the way if all you want is the sum, you can do that in MYSQL:

 

<?php
$con = mysql_connect("localhost","root","*****")
  or die('Could not connect: ' . mysql_error());
$db = mysql_select_db("testpos",$con);

$sql = "SELECT SUM(id) FROM sales";
$result = mysql_query($sql,$con);
$row = mysql_fetch_row($result);

$sum = $row[0];
echo $sum;
?>

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.