How to sum values stacked in different Rows? PHP PDO MYSQL - php

Let's say we have a very simple while row query script, for example:
<?php
include('conection.php');
$Verd = 'Verduras';
$smt = $con->prepare("select * from prodcts WHERE Type = :Verduras Order by PrdName ASC");
$smt->bindParam(':Verduras', $Verd, PDO::PARAM_STR);
$smt->execute();
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
{
echo '<th>'.nl2br($smr['PrdName']).'</th><th>'.nl2br($smr['SellType']).'</th><th>$'.nl2br($smr['Cost']).'</th>';
}
?>
Question:
How can i make than the results of the $smr['Cost'] Sum it up with the $smr['Cost'] of the rest/some others rows?
Any commentary, suggestion, question for improve the question or any kind of related answer looking to help & improve the question or result in the solution, etc would be much apreciated
Thanks in Advance!
PS: i check for another answers before, but mostly was mysql oriented, nevertheless i wanna check for a PHP more oriented solution, so to have more control about it and try to avoid (if possible) multiple querys.

Before you start the while loop, create a variable. In the while loop increase the variable by the value you want to add.
e.g:
$total = 0;
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
{
echo '<th>'.nl2br($smr['PrdName']).'</th>
<th>'.nl2br($smr['SellType']).'</th>
<th>$'.nl2br($smr['Cost']).'</th>';
$total += $smr['Cost'];
}
At the end, when you call $total, it will contain the sum.
<?php echo $total ?>
Hope it helps

If you need the sum of all rows, you can just create a variable before the while...
$Verd = 'Verduras';
$sum = 0;
$smt = $con->prepare("select * from prodcts WHERE Type = :Verduras Order by PrdName ASC");
$smt->bindParam(':Verduras', $Verd, PDO::PARAM_STR);
$smt->execute();
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
echo '<th>'.nl2br($smr['PrdName']).'</th><th>'.nl2br($smr['SellType']).'</th><th>$'.nl2br($smr['Cost']).'</th>';
$sum += $smr['Cost'];
}
echo $sum;
But if you need the value grouped $smr['PrdName'], just create a new array..
$Verd = 'Verduras';
$sum = 0;
$smt = $con->prepare("select * from prodcts WHERE Type = :Verduras Order by PrdName ASC");
$smt->bindParam(':Verduras', $Verd, PDO::PARAM_STR);
$smt->execute();
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
$prd[$smr['PrdName']][$smr['SellType']][0] += $smr['Cost'];
}
After that, you can display each line with a foreach...
It's easily to control using only SQL, but if you need to realize the treatment with PHP, i hope it helps.

Related

how to query once and display multiple times with where clause?

I want to learn how to query once and display in multiple boxes with
where clause?
like :
if status 1 ? : display in <div class="1"> elseif status 2 ?: <div class="2"> etc. etc.
I know my answer is in my question and I need to do if statements, but I dont know how to display while loop or foreach a few times with same query.
Here is my query :
$stmt = $pdo->prepare("SELECT * FROM categories");
$stmt->execute();
while($row = $stmt->fetch()){
}
I have searched on google got a few examples like this with for loop but I didnt find any examples with where claus.
$i;
$stmt = $pdo->prepare("SELECT * FROM categories");
$stmt->execute();
while($row = $stmt->fetch()){
}
for($i=0; $i<5; $i++){
}
I tried if statment without foreach loop :
if($status == 1){
foreach(){
echo "Display box 1";
}
}
if($status == 2){
foreach(){
echo "Display box 2";
}
}
Displaying only one post need while loop or foreach to display all posts with status 1
Thanks
While you could buffer multiple streams, read the entire dataset into a PHP array and search it or run multiple queries, all are unnecessary and inefficient. Just sort the query. Consider:
$stmt = $pdo->prepare("SELECT * FROM categories ORDER BY status");
$stmt->execute();
$prevstatus=-1;
print "<div style='display:none'>";
while($row = $stmt->fetch()){
if ($row['status']!=$prevstatus) {
$prevstatus=$row['status'];
print "</div><div class='$prevstatus'>";
}
print ....
}
print "</div>";
I don't know if I understand your question but:
$stmt = $pdo->prepare("SELECT * FROM articles");
$stmt->execute();
while($row = $stmt->fetch()){
echo "<div class=\"class_". $row["status"] ."\">div content</div>\n";
}
And - CSS classes can not begin with numbers or have only numbers as a name! In my example I use .class_x (where X is your value from database)

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

Using PDO to return a single set of values rather than an array

A very nice person on this site helped me with the following script (and it worked a treat)
<?php
$db = new PDO('mysql:host=HOST;dbname=DATABASE', $user, $pass);
$stmt = $db->prepare('
SELECT
yeast,
rating,
description,
weblink,
image,
sideimage
FROM dowdb_yeast_selector
WHERE
fruit = :fruit
ORDER BY
rating DESC
');
$stmt->bindParam(':fruit',$_POST['fruit'],PDO::PARAM_STR,50);
$stmt->execute();
How do I just echo side image (not as part of a while loop)?
I think (?) I need something like echo '$row[sideimage]' // how simple am I
All of the examples I have looked at so far do not fit my needs :-(
Use PDO::fetchAll, for example;
$stmt->execute();
$arrResults = $stmt->fetchAll();
//$arrResults will be multidimensional
//This will echo the first sideimage
echo $arrResults[0]['sideimage'];
If you want to echo all values of sideimage (ie: all rows), you'd have to iterate through the results;
foreach($arrResults as $arrRow) {
echo $arrRow['sideimage'] . PHP_EOL;
}
Links
pdo::fetchAll
You should use loop pdo::fetch()
while($abc = $stmt->fetch())
{
print_r($abc);
}
If you don't want to use loop try pdo::fetchAll()
$data = $stm->fetchAll();
You could use FETCH_ASSOC
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $res[0]['sideimage'];
or
foreach($res as $key=>$value) {
$image_val = $value['sideimage'];
}

MSSQL returns multiple rows into array, explode into one array per row

I have an MSSQL query where it SELECTS all rows that meet a specific criteria. In PHP I want to fetch that array, but then I want to convert it into one array per row. So if my query returns 3 rows, I want to have 3 unique arrays that I can work with.
I'm not sure how to go about this. Any help would be greatly appreciated!
Thanks, Nathan
EDIT:
$query = "SELECT * FROM applicants WHERE applicants.user_id ='{$_SESSION['user_id']}'";
$query_select = mssql_query($query , $connection);
if (mssql_num_rows($query_select) == 2){
$message = '2 students created successfully';
}
$i = 0;
while($row = mssql_fetch_array($query_select)) {
$student.$i['child_fname'][$i] = $row['child_fname'];
$student.$i['child_lname'][$i] = $row['child_lname'];
$i++;
}
$query_array1 = $student0;
$query_array2 = $student1;
You will notice from the code above that I am expecting two rows to be returned. Now, I want to take those two rows and create two arrays from the results. I tried using the solution that was give below. Perhaps my syntax is incorrect or I didn't understand how to properly implement his solution. But any help would be greatly appreciated.
$query = mssql_query('SELECT * FROM mytable');
$result = array();
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_assoc($query)) {
$result[] = $row;
}
}
mssql_free_result($query);
Now you can work with array like you want:
print_r($result[0]); //first row
print_r($result[1]); //second row
...
$i=0;
while( $row = mysql_fetch_array(query){
$field1['Namefield1'][$i] = $row['Namefield1'];
$field2['Namefield2'][$i] = $row['Namefield2'];
$field3['Namefield3'][$i] = $row['Namefield3'];
$i++;
}
or if you preffer an bidimensional array:
$i=0;
while( $row = mysql_fetch_array(query){
$result['Namefield1'][$i] = $row['Namefield1'];
$result['Namefield2'][$i] = $row['Namefield2'];
$result['Namefield3'][$i] = $row['Namefield3'];
$i++
}

PHP assign result from nested query into array

I need help in order to assign the results of a nested query into array. This is the scenario:
$Date_Collection = mysql_query("SELECT DISTINCT Date FROM TblDate");
while($date = mysql_fetch_array($Date_Collection)) // Loop through all the dates
{
$var_date = $date['Date'];
$result = mysql_query("select min(Speed) as Min_spd, max (Speed) as Max_spd, avg
(Speed) as Avg_spd from ... where Date= $var_date");
while($row = mysql_fetch_array($result))
{
echo "row[Min_spd]";
echo "row[Max_spd]";
echo "row[Avg_spd]";
}
}
The output from this query is like this:
Min_Spd |Max_Spd |Avg_Spd| Date|
12.0| 25.0| 20.4| 2012-10-01|
11.0| 28.0| 21.4| 2012-10-02|
10.0| 26.0| 23.4| 2012-10-05|
08.0| 22.0| 21.4| 2012-10-08|
I basically need to show the sum of Min_Spd, Sum of Max_spd, Sum of Avg_spd for all these dates. So, I thought that If I can assign these values into an array and later compute these sum from the array, it might be a good idea.
Can anyone please help me regarding this? Can I use an array to store the values and later access these values and calculate the sum of these values. If I can use an array, could anyone please show me the syntax of using array in PHP. I would really appreciate any help regarding this.
Is there any alternative way rather than using an array, such as creating a temporary table to save these values and later delete the temporary table. If a temporary table can be used, could you please show me how to do that. I could use the temptable for a single loop, but there is a nested loop and I don't exactly know what to do to create a temp table inside the nested loop to store all the values.
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
then later on you can do
foreach($data as $row) {
echo $row['Min_spd'];
echo ...
...
}
I don't know if the MySQL SUM function can be used to do that on te query, try it. But on this example, using arrays you should store the values and then use array_sum to return the sum of the elements. Something like this:
$min_spd = array();
$max_spd = array();
$avg_spd = array();
while($row = mysql_fetch_assoc($result))
{
$min_spd[] = $row['Min_spd'];
$max_spd[] = $row['Max_spd'];
$avg_spd[] = $row['Avg_spd'];
}
echo array_sum($min_spd);
It can also be done using variables to store and add the values:
$min_spd = 0;
$max_spd = 0;
$avg_spd = 0;
while($row = mysql_fetch_assoc($result))
{
$min_spd += $row['Min_spd'];
$max_spd += $row['Max_spd'];
$avg_spd += $row['Avg_spd'];
}
echo $min_spd;
I would first of all save yourself a nested query by doing the first query as:
$result = mysql_query("select Date, min(Speed) as Min_spd, max (Speed) as Max_spd, avg(Speed) as Avg_spd from ... group by Date")
And then create a running total for the sums as you're looping through each row:
$sumMinSpeeds=0;
$sumMaxSpeeds=0;
$sumAvgSpeeds=0;
while($row = mysql_fetch_array($result))
{
echo row['Min_spd'];
echo row['Max_spd'];
echo row['Avg_spd'];
$sumMinSpeeds += $row['Min_spd'];
$sumMinSpeeds += $row['Max_spd'];
$sumMinSpeeds += $row['Avg_spd'];
}
echo $sumMinSpeeds;
echo $sumMaxSpeeds;
echo $sumAvgSpeeds;
Instead of doing several MySQL queries in a loop, consider constructing such a query, which will return all the results you need.
SQL
First of all, it would make sense to use the GROUP SQL construct.
SELECT
s.Date date,
MIN(s.Speed) min,
MAX(s.Speed) max,
AVG(s.Speed) avg
FROM speed_table s
WHERE s.Date IN (SELECT DISTINCT d.Date FROM date_table d)
GROUP BY s.Date
It is important to understand what each part of this query does. If you run into any problems, consult the MySQL reference manual.
PHP
Forget about using mysql_* functions: they are deprecated and better implementations have emerged: PDO and mysqli. My example uses PDO.
try {
$dbh = new \PDO('mysql:dbname=my_db_name;host=127.0.0.1', 'dbuser', 'dbpass');
} catch (\PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = '...'; // This is the query
$stmt = $pdo->prepare($sql);
$stmt->execute();
You can now either iterate over the returned result set
while ($row = $stmt->fetch()) {
printf("%s; %s; %s; %s\n", $row['date'], $row['min'], $row['max'], $row['avg']);
}
or have the Statement object return the whole array by using
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);

Categories