English 中文(简体)
一、导 言
原标题:Sum column values while looping over a query result set [duplicate]

The following script shows the product and the quantity. Par example: t-shirt(1), boxershort(2).

Now I would like to show the sum of all items, in this case "3".

我怎么能够找到一个阵列——这sum?

$allItems = "";
$items = array();
$select_stmt = $db->prepare("SELECT CONCAT(product,   ( , quantity, ) ) AS ItemQty, price 
FROM database");
$select_stmt->execute();
while ($row = $select_stmt->fetch(PDO::FETCH_ASSOC))
{
    $items[] = $row["ItemQty"];
}
$allItems = implode(", ", $items);
最佳回答

you should do this:

<?php
$allItems = "";
$items = array();
$select_stmt = $db->prepare("SELECT CONCAT(product,   ( , quantity, ) ) AS ItemQty, price 
FROM database");
$select_stmt->execute();
while ($row = $select_stmt->fetch(PDO::FETCH_ASSOC))
{
    preg_match( /[0-9]+/ , $row["ItemQty"], $match);
    array_push($items, (int)$match);
}
echo array_sum($items);
$allItems = implode(", ", $items);
?>
问题回答

Avoid selecting data in a way that fits the purpose of displaying it. What you should do instead is grab only the data:

$select_stmt = $db->prepare("SELECT product, quantity, price FROM database");

Then you can easily do calculations with raw numbers:

while ($row = $select_stmt->fetch(PDO::FETCH_ASSOC))
{
    $items[] = $row["quantity"];
}
$sum = array_sum($items);

and have the display value created in PHP:

$displayItem = sprintf( %s (%d) , $row[ product ], $row[ quantity ]);

如果你坚持,你可以直接从问询中看到这种显示,然后又把它作为另一个领域:

$select_stmt = $db->prepare("SELECT product, quantity, price, CONCAT(product,   ( , quantity, ) ) AS ItemQty FROM database");

This way you still have quantity as a number to do calculations with and ItemQty to use for displaying purposes.





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签