简体   繁体   中英

Error when adding total quantity fetched by MYSQL Query in PHP

I want to add the quantity of pants to display the total pants in the database but it only shows nothing.. this is the coding.. is my logic is wrong?

<?php
if(is_resource($r) and mysql_num_rows($r)>0)
{
       while ($r = mysql_fetch_array($q))
       {
            $p = mysql_query("SELECT qtt FROM stock_request WHERE branch_id = 'bachok' AND type = 'Pants'") or die ("Error: " . mysql_error());

            $tp = $tp + $p;
        }
        echo $tp;
                          }
?>

Your logic is wrong:

$p = mysql_query("SELECT qtt FROM stock_request WHERE branch_id = 'bachok' AND type = 'Pants'") or die ("Error: " . mysql_error());

should be:

$result = mysql_query("SELECT qtt FROM stock_request WHERE branch_id = 'bachok' AND type = 'Pants'") or die ("Error: " . mysql_error());
$row = mysql_fetch_assoc($result);
$p = $row['qtt'];

Wrong Logic as mysql_query() returns a resource on success, or FALSE on error. It does not return the value(quantity in your case).

In order to fetch a value in an array, use mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both.

Initialise $tp=0 before while loop

Replace $tp = $tp + $p; with

$tp=$tp+$r[0]

Here is the complete code:

<?php

       $p = mysql_query("SELECT qtt FROM stock_request WHERE branch_id = 'bachok' AND type = 'Pants'") ;
       $tp=0;
       while ($r = mysql_fetch_array($p,MYSQL_NUM))
       {
             $tp = $tp + $r[0];
       }
        echo $tp;

?>

UPDATE: What's the meaning of $r[0]?

mysql_fetch_array can be used in three ways:

  • mysql_fetch_array() with MYSQL_NUM

  • mysql_fetch_array() with MYSQL_ASSOC

  • mysql_fetch_array() with MYSQL_BOTH

I had used $r=0 ie. mysql_fetch_array with MYSQL_NUM.

In this case, you only get number indices. For example :

$result = mysql_query("SELECT a,b,c,d,e FROM mytable");

$row = mysql_fetch_array($result, MYSQL_NUM)) 

$row [0] means value of a

$row [ 1] means value of b

$row [ 2] means value of c

............

$row[4]=means value of e.

Thus in your query, $r[0] refers to value of qtt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM