I am attempting to get the summation of a set of float values in a column of a table. I did a select query that pulls five sets of integers. A while function with a fetch_row is used to get the array. I use a foreach function to get the sum, however, the echo or printf does not give me one single variable. Instead I get an ever increasing value as each integer is added to the summation of the values before it. I have tried the array_sum, which doesn't work either. Please help! I have looked at every possible question in Stackoverflow.
<?php
//Check if at least one row is found
if($results2->num_rows > 0) {
//Loop through results and fetch as an array
$total = 0;
while($rows = $results2->fetch_row()){
foreach($rows as $sum)
$total += $sum;
printf($total.'<br/>');
}
}
?>
You're printing the total inside the loop, so you see all the subtotals. If you just want to see the final result, print it when the loop is done.
foreach ($rows as $sum) {
$total += $sum;
}
printf("%d<br/>", $total);
Also, when you use printf, the first argument is a format string. The values come after, and they get substituted into the format.
You can also use array_sum:
printf("%d<br/>", array_sum($rows));
Note that these are summing up all the columns in each row, not a single column in the whole table.
Related
I'm new to PHP and I am stuck trying to understand this basic while/for loop. There's a couple of things I just wanted to clarify. Here is the code:
while ($row = $sth->fetch (PDO::FETCH_NUM))
{
print ("<tr>\n");
for ($i = 0; $i < $sth->columnCount (); $i++)
{
print ("<td>" . htmlspecialchars ($row[$i]) . "</td>\n");
}
print ("</tr>\n");
}
I know the while is evaluating for true, so it's getting the result set of the query, and then printing the tags.
However I'm stuck on the
for ($i = 0; $i < $sth->columnCount (); $i++)
I know that the first expression evaluates once, the second evaluates at the beginning and only moves on if it's true, and the third increments by +1. But what exactly is this doing in literal terms and why is it "columnCount"?
This is a PDO database setup.
In literal terms, the $row is a row fetched from the database, from code that lives above in a statement which didn't make your cut. It then sends an iterator into every field of the row (getting its number from the columnCount function(http://php.net/manual/en/pdostatement.columncount.php), and prints out some html.
Generally, this kind of iterator is 'less-than-ideal' code for several reasons. Generally, coding practices in PHP prefer to use foreach instead of a for iterator unless one actually needs the count as we pass through, ostensibly why the fetch is done as FETCH_NUM, although it is never used.
while ($row = $sth->fetch())
{
print ("<tr>\n");
foreach ($row as $key=>$value)
{
print ("<td>" . htmlspecialchars($value) . "</td>\n");
}
print ("</tr>\n");
}
What that line does is making it possible to iterate on each column of the specific $row. $sth->columnCount() returns the number of columns for what seems to be a table data structure.
On the other hand, the for loop will execute the print statement i times, where i will be 0 when starting and will be increasing itself to be as the number of columns returned by $sth->columnCount() minus 1.
Why minus 1?
Because usually in programming you start counting from 0 instead of 1.
So $row[0] represents the 1st column of your row, $row[1] represents the 2nd column, and so on, until you reach the last column which is $row[$sth->columnCount() - 1]
The for loop is starting at the beginning of the dataset and evaluating until it reaches the end of the dataset.
The dataset will always start at 0, until $i is no longer less than the value of columnCount() it will continue.
$sth is some instantiated object (variable) which has a method called columnCount(). That method likely returns the total number of columns which $sth is representing.
It may also help to say that this for loop can be rewritten as a while loop:
$i = 0;
while($i < $sth->columnCount()) {
// do something
$i++;
}
this will iterate through all fields of one row.
columnCount()returns the number of fields in your statement.
So if your statement is:
SELECT a,b,c,d FROM test;
columnCount() return 4.
I´m new to PHP and SQL and it´s the first time I post here, hope I do it right =)
I need to find out the numeric index from an certain field in my database. Thing is I´m not done with the database structure yet, so for this specific field I´d like to have it automated so I won't have to change the code every time I add or remove columns.
I also need it to have BOTH index types so I can call the columns by name in part of the code and by index for automated parts of it.
I´ve managed to achieve the result I wanted trough an very ugly code, because all the array_search and array_keys I´ve tried didn´t work out for some reason.
Here is the snippet of my working but ugly code. Do you have an more elegant solution?
Thanks in advance for your answers, and for all I´ve learned so far from reading other peoples questions!
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes) or die(mysql_error());
$c = 0; // This block is to find out where the column "cont1" is and assign it to $cont1
$d=array_keys($student);
$cont1=0;
foreach ($student as $a=>$b){
if ($a==='cont1') {
$cont1=$d[$c-1];
}
$c++;
}
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$students[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$students[$i+2]."</li>";
echo "</ul></p>";
}
}
Finding the numeric index:
$student = mysqli_fetch_array($dadosRes,MYSQLI_ASSOC) or die(mysql_error());
$numericIndex = array_search("cont1",array_keys($student));
Giving MYSQLI_ASSOC will force the query to fetch only the associative keys; otherwise it will give you both numeric and associative array.
PHP function, array_search in this case, requires the third parameter set to TRUE:
<?php
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes, MYSQLI_BOTH) or die(mysql_error());
$student_keys = array_keys($student);
$cont1 = $student_keys[array_search("cont1", $student_keys, true) - 1];
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$student[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$student[$i+2]."</li>";
echo "</ul></p>";
}
}
?>
MYSQLI_BOTH is used in the mysqli_fetch_array function because first the array is searched for the column name, then later the array is looped over with numeric indexes. This results in the $student array having integer 0 as the first element and therefore causing array_search to choke. Adding true as the third parameter causes a === comparison unchoking the function. :) (Explanation: PHP array_search consistently returns first key of array )
I'm trying to show the max value of column teams from mysql. Above the while loop I've selected teams from my mysql table and then as you can see in my code below I have included max($teams) - but it is returning an error? Where am I going wrong.
while ($rows = mysql_fetch_assoc($result)) {
$teams = $rows['teams'];
if($teams > "1") {
echo '<div class="bestbettor">'.'<span class="redtext">'."Bettor: ".'</span>'. $rows['username'].'</div>';
echo '<div class="bestbettor">'.'<span class="redtext">'." Bet: ".'</span>'.max($teams). " team accumulator".'</span>'.'</div>';
}
}
you must pass an array to max().
$teams = $rows['teams']; // saves as string.
if your teams were delimited by a comma then you could do something like:
$teams = explode(",",$rows['teams']); // saves as array
then you could do max()
If one parameter is given to max() it has to be an array of values of which max() will return the highest value in that array. It seems like you've just given it a single string.
foreach ($_POST['ECL'] as $lt) {
//SQL select statements are run. Each $lt is a where condition where results are obtained from the DB.
}
I want to take a count of each result and sum this up. The total would be records obtained. I can get the record count for each individual $lt, but I am unable to sum them. All help would be appreciated.
[update] the number of $lt is not fixed. $lt can be 1,2,3,4... Counter such as $i++ does no work
Set a counter before the loop, increment it during the loop, retrieve the sum at the end. Simple...
Try using mysql_num_rows or mssql_num_rows - they return the number of rows in a result
$count = 0; // setup count variable
foreach ($_POST['ECL'] as $lt) {
//SQL select statements are run. Each $lt is a where condition where results are obtained from the DB.
$count += mysql_num_rows($result); // add results count to our counter
}
echo $count; // this will be the total number of rows the queries returned
Your question says that you're adding the result rows from each $lt into an array (I don't see that in the posted code though).
If that's the case, and you're inserting one array record per row, the length of the array should serve as your count.
What I want to do here is to be able to assign the values from sql query into arrays.
And then compute for the total.
<?php
include('conn.php');
$qreports=query_database("SELECT S_PRICE, PID, QTY_PUR, ITEM_ID, CUSID, CNUM, Cust_Name, TDATE FROM prod_table, customer_credit, sales_trans_items WHERE prod_table.PID=sales_trans_items.ITEM_ID AND sales_trans_items.CNUM=customer_credit.CUSID AND sales_trans_items.TDATE='2011-02-06 09:14:09'","onstor",$link);
$grandtotal=0;
$customer="";
while($qrep=mysql_fetch_assoc($qreports)){
$pid=$qrep['PID'];
foreach ($pid as $k => $v) {
$sids=$v;
$qtypur=$qrep['QTY_PUR'][$k];
$sprice=$qrep['S_PRICE'][$k];
$customer=$qrep['Cust_Name'][$k];
$tdate=$qrep['TDATE'][$k];
$stot=$qtypur * $sprice;
$grandtotal =$grandtotal + $stot;
}
}
echo "Customer: ". $customer."<br/>";
echo "Profit: ". $grandtotal;
?>
I tried the query on phpmyadmin before I place it in the code, and it output this:
I think you misunderstood how mysql_fetch_assoc works: Every call returns one row from the result set. $grep is an array with structure columnname => value.
That also means that $qrep['PID'] cannot be an array and your foreach loop won't work. In every loop, $qrep['PID'] contains one of the values you see in the PID column in your screen shot.
I suggest you add print_r($qreq); in your while loop so you get more familiar with the structure of the array.
As each $qrep is an array itself, creating a result array is just adding each of these to a new array:
$result = array();
while(($qrep=mysql_fetch_assoc($qreports))) {
$result[] = $qrep;
}
Now you are performing some more computation where I am not sure what you want to get in the end but it seems you are multiplying each QTY_P with S_PRICE:
$total = 0;
foreach($result as $report) {
$total += $report['QTY_P'] * $report['S_PRICE'];
}
(You could however also compute this in your while loop)
Assuming you want to get the overall sum and the sum for each customer:
$total = 0;
$total_per_customer = array();
foreach($result as $report) {
$customer = $report['Cust_Name'];
if(!array_key_exists($customer, $total_per_customer)) {
$total_per_customer[$customer] = 0;
}
$price = $report['QTY_P'] * $report['S_PRICE'];
$total_per_customer[$customer] += $price;
$total += $price;
}
In the end, $total_per_customer is an array with customer names as keys and the sum of the prices as values. $total will contain the sum of all prices.
You question is a bit unclear, but i think the answer wont be far a way from the following suggested references:
As you loop through the rows use
something like $array[] =
$qrep['columnName'] to populate an
array.
Then, check out PHP's array_sum().