PHP array for loop - php

I want to show the array value $result[] from the for loop calculation. However, it shows me nothing on the page. Is there is anything wrong in the below code?
$sql= "SELECT * FROM items where itemID =3 ";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_array($result1)){
$quantity[] = $row ['quantity'];
$month[] = $row ['month'];
}
$alpha = 0.3;
for($i = 1; $i > 12; $i++){
$result[$i] = ($quantity[$i] - $result[$i-1]) * $alpha + $result[$i-1];
}
foreach ($result as $key => $value ){
echo "$value";
}

Your for loop has an error. You have
for($i = 1; $i > 12; $i++)
but it should be
for($i = 1; $i < 12; $i++)

This is not directly the answer to your question, but there are few things that hasn't been mentioned that concern the way you query and process your data:
Your SELECT statement doesn't have specific order specified. Since order of records is not preserved you can get records out of correct order and get invalid calculations. Use ORDER BY (e.g. ORDER BY month) or make use of month values and extract exactly previous month's value from array(s) (if it is what you're doing in your code).
Your current code relies on the fact that the resultset from DB will contain (at least) 12 records. If for some reason it will produce less records your for loop will brake.
It's uncertain from the information in the question but it looks like you might need a year in your query unless the table contains records only for one year.
Now, you can calculate the whole thing on DB side with a query like this
SELECT i.month,
COALESCE((i.quantity - p.quantity) * 0.3 + p.quantity, 0) value
FROM items i LEFT JOIN items p
ON i.itemID = p.itemID
AND i.`year` = p.`year`
AND i.month = p.month + 1
WHERE i.itemID = 3
AND i.`year` = 2013
ORDER BY month
SQLFiddle
That's assuming (and I'm not sure about that) you actually need to read previous month's quantity values for your calculations and month column is of integer type

There is an obvious flaw in the logic. You try to get the $i index form $quantity. However, you can't be sure $quantity will have this index.
Supposing that itemId is not the primary key, I would do something like this:
$sql = "SELECT * FROM `items` WHERE `itemID` = 3";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_assoc($result1)){
$quantity[] = $row ['quantity'];
}
$alpha = 0.3;
$i = 1
foreach ($quantity as $elem) {
if ($i >= 12)
break;
$result[$i] = ($elem - $result[$i-1]) * $alpha + $result[$i-1];
$i++
}
foreach ($result as $value ){
echo $value;
}

Related

Getting total from mysql query with array

I have this code and i would like to get total combination of all categories
my code so far
for ($k = 0; $k < 4; $k++) {
$result= $DB->query("SELECT total FROM ".$DB->prefix("mystat")." WHERE year='$year' AND category='$categoryname[$k]'");
$row = $DB->fetchArray($result);
$total=$row['total'];
echo $total++;
}
let say i have this data
A - 1
B - 2
C - 3
my current output
123
my desired output
6
How do i correct this ?
It is because you are doing echo in loop. And also you logic is wrong. change your code like:
$total = 0;
for ($k = 0; $k < 4; $k++) {
$result= $DB->query("SELECT total FROM ".$DB->prefix("mystat")." WHERE year='$year' AND category='$categoryname[$k]'");
$row = $DB->fetchArray($result);
$total +=$row['total'];
}
echo $total; // DO echo here
Also if you don't need categories and total separately and only need sum of all then its better to use SUM with group by category in sql.

can't get the logic to restart looping

I have 15 databases 1,2,3,4, ... 15
and I have the variable $i default at 1 and each time the $i count gets to 3, $i restarts the looping from 1 again until 3 and it will stop until value from database is done counting.
$detailPsycho = mysql_query("SELECT * FROM `psycho` WHERE `flag` = 2 ") or die(mysql_error());
while($detail = mysql_fetch_array($detailPsycho)){
for($i = 1;$i<=3;$i++){
echo $detail['sequence']."&".$i." <br>";
}
}
and run over like this :/
1&1
1&2
1&3
2&1
2&2
2&3
You try to do a loop (for{}) in a loop (while{}) which is a complicated way of doing something trivial. This is the "while+for" result :
$detailPsycho = mysql_query("SELECT * FROM `psycho` WHERE `flag` = 2 ") or die(mysql_error());
i = (int) 1;
while($detail = mysql_fetch_array($detailPsycho)) {
echo $detail['sequence']."&".$i." <br>";
$i++;
if ($i > 3) $i = 1;
}

How do I fix this php to include full list from array?

$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
for ($i = 1; $i < count($array); ++$i) {
$userids = $array[$i].',';
$q2 = mysql_query("SELECT * FROM item WHERE approved = 1 AND id IN(".$userids."0)");
echo $userids;
//NOTE: my echo is spitting out "18622,44968,44968," but when using $userids in mysql query it doesn't include the full list of numbers
}
}
I put }'s after mysql query to try to include variable in the for loop, if i close brackets before query $userids only prints last number from array.
Close the parenthesis before your query and use concatenation instead of re-assigning $userids on each iteration:
$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
for ($i = 1; $i < count($array); ++$i) {
$userids .= $array[$i].',';
// ^ missing the period here
}
}
$q2 = mysql_query("SELECT * FROM item LEFT JOIN subcategory
ON item.subcategory_id=subcategory.subcategory_id LEFT JOIN genre ON item.genre_id=genre.genre_id WHERE approved = 1 AND broken = 0 AND id IN(".$userids."0)");
echo $userids;
You could also just get rid of the for-loop and use implode():
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
$userids .= implode(',', $array) + ',';
}
While this may fix the issue, know that this isn't very efficient nor maintainable. It would make more sense to use SQL JOIN syntax to combine a user's recent views with the sub-categories all in one query.

PHP Order by ASC not working on decimal type

Have a quick question regarding ORDER. I have a list of scores I am displaying in a high scores table using php. I need the lowest decimal number to display in 1st place, however when I try to use the ASC command, no results display. But if I use DESC the results do display, but in the opposite order to what I need (lowest decimal displays last).
Here is the "working" code that displays the scores, but in the wrong order.
$query = mysql_query("select reflex,playerID from users_stats order by reflex DESC limit 10")or die(mysql_error());
$ranking = 0;
while ($row = mysql_fetch_array($query)) {
if ($row[reflex] <= 0) break;
$ranking = $ranking + 1;
$rankingdisplay = doRankPosition($ranking);
print "<tr><td><b>$rankingdisplay</b></td><td>$row[playerID]</td><td>$row[reflex]</td></tr>";
if ($ranking >= 10) break;
}
Here is the code that displays nothing (no results are returned).
$query = mysql_query("select reflex,playerID from users_stats order by reflex ASC limit 10")or die(mysql_error());
$ranking = 0;
while ($row = mysql_fetch_array($query)) {
if ($row[reflex] <= 0) break;
$ranking = $ranking + 1;
$rankingdisplay = doRankPosition($ranking);
print "<tr><td><b>$rankingdisplay</b></td><td>$row[playerID]</td><td>$row[reflex]</td></tr>";
if ($ranking >= 10) break;
}
I have also tried this (default);
$query = mysql_query("select reflex,playerID from users_stats limit 10")or die(mysql_error());
$ranking = 0;
while ($row = mysql_fetch_array($query)) {
if ($row[reflex] <= 0) break;
$ranking = $ranking + 1;
$rankingdisplay = doRankPosition($ranking);
print "<tr><td><b>$rankingdisplay</b></td><td>$row[playerID]</td><td>$row[reflex]</td></tr>";
if ($ranking >= 10) break;
}
And again, no results display....
The reflex score is being stored in a MySQL database using decimal(4,3) default None. Can anyone point me in the right direction? I have tried to google it, but can't seem to find anything specific to what I need. I assume it is something to do with decimal??
Thanks in advance.
*EDITED - I do appreciate any answers/advice, however I am very new to php and still desperately trying to learn :/
Probably you have 0 in column "reflex" and line
if ($row[reflex] <= 0) break;
made exit from cycle

Query Multiple Conditions

I am keeping track of a few things on my site and im using a lot of queries because they need different conidtions
for example
$example = mysql_query("SELECT column FROM table WHERE column = 'Value1'");
$example_row = mysql_num_rows($example);
$example1 = mysql_query("SELECT column FROM table WHERE column = 'Value2'");
$example_row1 = mysql_num_rows($example1);
And so on, the value is always different so im having trouble finding a way to make this in to one query where i could still get different rows count for different values, is it possible?
I could test the row to see if it matches the value
if ($row == 'value'){
}
Multiple times but it still seems bad
Use IN()
SELECT column FROM table WHERE column IN('Value1', 'Value2');
I believe you want the count per value:
$values = ["value1", "value2", ...];
$query = "SELECT ";
for($i = 0; $i < count($values); $i++)
{
$query .= "SUM(IF(column = '$values[$i]')) AS v$i";
if($i != count($values) - 1)
$query .= ","; //Only add ',' if it's not the last value
$query .= " "; //We need the spaces at the end of every line
}
$query .= "FROM table";
//Let mysql do its work, run the query etc., store the resultset in $row;
Now you can dynamically iterate through the resultset:
$results = [];
for($i = 0; $i < count($values); $i++)
{
$string = "v"+ $i;
$results[] = $row[$string];
}

Categories