Dynamically add into array and retrieve sum - php

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.

Related

Query DB based off array order / sort array based off another array's values

So I feel like there is a simple solution to this, but my mind is going blank.
I have an array of IDs, like so:
//array in no particular order
$arr1 = array(456, 5, 9, 2, 470, 3);
Now, those are the IDs (primary key) of rows in my database. I need to get the information for all of those, while maintaining that order. I can query the DB just fine, and get results, but what I can't figure out is how to maintain that order. So the result is I want to be able to iterate over the result and spit out the information in this specific order.
Is there a way to tell the MYSQLI query to sort the IDs by this array? Or once I get the result, is there a way to re-order the result to reflect the order in the given array?
Use this
SELECT * FROM table WHERE id IN (5,9,17,19,456) ORDER BY id ASC;
So, you will get rows that match any id and order it ascending.
I've managed to solve my problem.
$unorderedArray = array();
$orderedArray = array();
while($a = mysqli_fetch_assoc($r)) {
array_push($unorderedArray, $a);
}
for($i = 0; $i < sizeof($list); $i++) {
for($ii = 0; $ii < sizeof($unorderedArray); $ii++) {
if($list[$i] == $unorderedArray[$ii]['id']) {
array_push($orderedArray, $unorderedArray[$ii]);
}
}
}
So first I take the result from the DB and create a multi-dimensional array with it to make it easier to work with. Then I loop through the first array, which is the order I want, and loop through the result array. When there is a match, I push that into a newly constructed array.
The order is preserved because the array's have the same ID's, one just has more information that the other. So the order, the outermost loop, will match every time. This allows me to put the entirety of the DB result in an array with the order of my $list array.

PHP - Explain this while/for loop to me

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.

Array_sum of a fetch_row

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.

Wrong parameter count for max()

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.

MYSQL PHP while loop, do something if there aren't a given amount of rows returned

I'm trying to figure out the best way to do something like this. Basically what I want to do (in a simple example) would be query the database and return the 3 rows, however if there aren't 3 rows, say there are 0, 1, or 2, then I want to put other data in place of the missing rows.
Say my query returns 2 rows. Then there should be 1 list element returned with other data.
Something like this:
http://i42.tinypic.com/30xhi1f.png
$query = mysql_query("SELECT * FROM posts LIMIT 3");
while($row = mysql_fetch_array($query))
{
print "<li>".$row['post']."</li>";
}
//(this is just to give an idea of what i would likkeee to be able to do
else
{
print "<li>Add something here</li>";
}
You can get the number of items in the resultset with mysql_num_rows. Just build the difference to find out how many items are "missing".
There are three ways I can think of, get the row count with mysql_num_rows, prime an array with three values and replace them as you loop the result set, or count down from three as your work, and finish the count with a second loop, like this:
$result = db_query($query);
$addRows = 3;
while ($row = mysql_fetch_assoc($result){
$addRows--;
// do your stuff
}
while ($addRows-- > 0) {
// do your replacement stuff
}
If you dont find a row, Add extra information accordingly.
$query = mysql_query("SELECT * FROM posts");
for($i=0;$i<3;$i++){
$row = mysql_fetch_array($query);
if($row){
print "<li>".$row['post']."</li>";
}
//(this is just to give an idea of what i would likkeee to be able to do
else{
print "<li>Add something here</li>";
}
}
Assuming you store the rows in an array or somesuch, you can simply do some padding with a while loop (depending how you generate the other data):
while (count($resultList) < 3) {
// add another row
}

Categories