can't get the logic to restart looping - php

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;
}

Related

How to limit foreach for multiple table as a one

I have the issue with LIMIT with foreach using PHP.
Basics: I have 50 different tables and in every table I have 2 rows.
When I try to add LIMIT 1 to $$modules_for_all, then I see 50 rows, but I want to see only 1. If I add LIMIT 2, then I see 100 rows.
How I can connect all these tables as a one LIMIT 1 to get 1 row in foreach?
<?php
for ($i = 1; $i <= 50; $i++) {
// $array_table_name contains names with tables
$table_names = $array_table_name[$i];
$modules_for_all = 'g_module_for_all_'.$i;
$$modules_for_all = $db->QueryFetchArrayAll("SELECT * FROM $table_names WHERE user='1' LIMIT 1");
}
for ($i = 1; $i <= 50; $i++) {
$modules_for_from = ${"g_module_for_all_$i"};
foreach ($modules_for_from as $m_foreach_as) {
echo $m_foreach_as['id'];
}
}
Example tables:
table_1
id date_added
1 2018-12-01 00:00:00
2 2018-12-02 00:00:00
table_2
id date_added
1 2018-12-03 00:00:00
2 2018-12-04 00:00:00
table_3
id date_added
1 2018-12-05 00:00:00
2 2018-12-06 00:00:00
Example foreach:
<?php
$array_table_name_1 = 'table_1';
$array_table_name_2 = 'table_2';
$array_table_name_3 = 'table_3';
$for_table_1 = $db->QueryFetchArrayAll("SELECT * FROM $array_table_name_1 WHERE id='1' LIMIT 1 ORDER BY date_added");
$for_table_2 = $db->QueryFetchArrayAll("SELECT * FROM $array_table_name_2 WHERE id='1' LIMIT 1 ORDER BY date_added");
$for_table_3 = $db->QueryFetchArrayAll("SELECT * FROM $array_table_name_3 WHERE id='1' LIMIT 1 ORDER BY date_added");
foreach ($for_table_1 as $m_foreach_as) {
echo $m_foreach_as['id'];
}
foreach ($for_table_2 as $m_foreach_as) {
echo $m_foreach_as['id'];
}
foreach ($for_table_3 as $m_foreach_as) {
echo $m_foreach_as['id'];
}
// Now result is '111' but I want only '1' (realted to make LIMIT 1 to all foreach)
The only way to connect the tables is by using a UNION. So you will need to build one large UNION query and then perform the select after the loop:
$tables = array();
for ($i = 1; $i <= 50; $i++) {
// $array_table_name contains names with tables
$table_names = $array_table_name[$i];
$tables[] = "(SELECT * FROM $table_names WHERE user='1')";
}
$query = implode(" UNION ", $tables) . " ORDER BY date_added LIMIT 1";
$result = $db->QueryFetchArrayAll($query);
foreach ($result as $row) {
echo $row;
}
You are gonna have to use UNION ALL for summing this rows together before ordering and limiting the results.
But keep in mind that a query like this will only work if all the tables in your array have the same structure. If they do not, then you will have to be specific in the query to make them have the same fields.
$array_table_name = [
'table_1',
'table_2',
'table_3',
];
$search_id = 1;
$selectsArray = [];
foreach ($array_table_name as $table_name) {
$selectsArray[] = "SELECT * FROM $table_name WHERE id='$search_id'\n";
}
As you see, I am using foreach() and not for() so you won't update the for by decreasing/increasing the number of tables in the array. So to finally have:
$selectsUnion = implode("UNION ALL\n", $selectsArray) . "ORDER BY date_added \nLIMIT 1";
You can see the code tested and query mounted here: https://3v4l.org/HXH2K
I solved my problem using this: foreach ($modules_for_from as $m_foreach_as) if ($tmp++ < 1) {

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.

Select Query in Group of 10

I followed one link here, and modified my code accordingly. What I am trying to do achieve is for example a table name media_ids contains 45 rows(which is dyanamic), I want to divide the no of rows in a group of 10 rows minimum (in my case four groups of 10 rows and 1 group of 5) and execute code of each group per hour.
For example from select record from id 1 to 10 then second hour from 11 to 20 and so on unless fetches the last record and start again from id 1.
I added a tracker, which check whats the current limit and proceed.But its giving me the required result what I am trying to achieve.
<?php
require('inc/dbConnect.php');
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointer10=$lastPointer+10;
$currentMediaQuery = "select * from media_ids where id > ".$lastPointer." limit ".$lastPointer.",".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
if ($lastPointer + 10 > 40) {
$lastPointer = 1;
} else {
$lastPointer += 10;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");
?>
I am assuming you are calling this script every hour via ajax/Js...
In your code if you delete some data from another script you may find your first row id i.e 100 !
require('inc/dbConnect.php');
$limit = 10 ;
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointerRes = mysqli_fetch_assoc($lastPointerResult);
$lastPointer = empty($lastPointerRes['tracker']) ? 0 : $lastPointerRes['tracker'] ;
$lastPointer10=$lastPointer* $limit;
$currentMediaQuery = "select * from media_ids limit ".$limit." OFFSET ".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
//do a total row count query here and set as value of $total rather than 40
$total =40 ;
$flag = ceil($total/$limit);
if ($lastPointer == $flag) {
$lastPointer = 0;
} else {
$lastPointer ++;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");

PHP array for loop

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;
}

PHP sorting array output

UPDATE 2 (Players Handicap Index Calculation)
$sql3 = "SELECT roundID FROM rounds WHERE userID='$userID'";
$result3 = mysql_query($sql3) or die(mysql_error());
$total_rounds = mysql_num_rows($result3);
//CALCULATE USER HANDICAP INDEX IF TOTAL_ROUNDS > 4
if($total_rounds > 4){
if($total_rounds<7) { $score_count = 1; }
elseif($total_rounds<9) { $score_count = 2; }
elseif($total_rounds<11) { $score_count = 3; }
elseif($total_rounds<13) { $score_count = 4; }
elseif($total_rounds<15) { $score_count = 5; }
elseif($total_rounds<17) { $score_count = 6; }
elseif($total_rounds<18) { $score_count = 7; }
elseif($total_rounds<19) { $score_count = 8; }
elseif($total_rounds<20) { $score_count = 9; }
else { $score_count = 10; }
$sql2 = "SELECT differential FROM rounds WHERE userID='$userID' ORDER BY date DESC LIMIT 20";
$result2 = mysql_query($sql2) or die(mysql_error());
$diff_results = array();
while($row = mysql_fetch_assoc($result2)){
$diff_results[] = $row['differential'];
}
sort($diff_results);
$diff_results = array_slice($diff_results, 0, $score_count);
$handicapIndex = array_sum($diff_results) / $score_count * 0.96;
$handicapIndex = (floor($handicapIndex * 10)) / 10;
Hopefully this will give you all and idea of how I calculate a players handicap index. Now I would like to show the player (user) the rounds (date ordered) that are used to calculate his index.
Always appreciative!
UPDATE (structure of rounds table)
roundID - auto incrementing primary key
userID - INT
courseID - INT
tee - VARCHAR
differential - FLOAT
date - DATE
I am struggling to even get started with this feature I am trying to implement. Any help would be much appreciated.
I have a set of mysql db results I would like to sort by field differential. I pull them out of the db like this:
$sql4 = "SELECT * FROM rounds WHERE userID='$userID' ORDER BY date DESC LIMIT 20";
$result4 = mysql_query($sql4) or die(mysql_error());
$total_rounds = mysql_num_rows($result4);
As you can see above I counted the rows returned to run through this if-elseif-else statement to figure out how many scores I need to highlight with different css:
if($total_rounds<7) { $score_count = 1; }
elseif($total_rounds<9) { $score_count = 2; }
elseif($total_rounds<11) { $score_count = 3; }
elseif($total_rounds<13) { $score_count = 4; }
elseif($total_rounds<15) { $score_count = 5; }
elseif($total_rounds<17) { $score_count = 6; }
elseif($total_rounds<18) { $score_count = 7; }
elseif($total_rounds<19) { $score_count = 8; }
elseif($total_rounds<20) { $score_count = 9; }
else { $score_count = 10; }
For example, if $total_rounds = 16 my $score_count would be 6.
Now I need to take this data set of 16 rows and spit it out with php so I maintain my ORDER BY date while applying a different css format to the 6 figured in the above if-elseif-else statement. The $score_count is figured because I need to highlight (aka apply different css) to the 6 lowest scores of the 16 row data set WHILE maintaining my date order.
The desired output would look like this (with the * denoting the separate css format *).
01-08-2013 - 16
01-07-2012 - 1 *
01-06-2013 - 15
01-05-2012 - 2 *
01-04-2013 - 14
01-03-2012 - 3 *
01-02-2013 - 13
01-01-2012 - 4 *
12-31-2012 - 12
12-30-2012 - 5 *
12-29-2012 - 11
12-28-2012 - 6 *
12-27-2012 - 10
12-26-2012 - 9
12-25-2012 - 8
12-24-2012 - 7
Please let me know if you have questions.
Thanks
There are couple of steps that you will have to follow.
1) Sort the results with score(differential) and get the ids of the six records having lowest score.
$sql4 = "SELECT * FROM rounds WHERE userID='$userID' ORDER BY differential LIMIT 20";
$result4 = mysql_query($sql4) or die(mysql_error());
$total_rounds = mysql_num_rows($result4);
if($total_rounds<7) { $score_count = 1; }
elseif($total_rounds<9) { $score_count = 2; }
elseif($total_rounds<11) { $score_count = 3; }
elseif($total_rounds<13) { $score_count = 4; }
elseif($total_rounds<15) { $score_count = 5; }
elseif($total_rounds<17) { $score_count = 6; }
elseif($total_rounds<18) { $score_count = 7; }
elseif($total_rounds<19) { $score_count = 8; }
elseif($total_rounds<20) { $score_count = 9; }
else { $score_count = 10; }
$idsArray = array();
for($i=0; $i<$score_count; $i++){
$dets = mysql_fetch_array($result4);
$idsArray[] = $dets['roundID'];
}
2) Loop over records and match the id in array that you have made by first step. If id matches apply CSS otherwise not.
$sql4 = "SELECT * FROM rounds WHERE userID='$userID' ORDER BY date DESC LIMIT 20";
$result4 = mysql_query($sql4) or die(mysql_error());
while($dets = mysql_fetch_array($result4)){
if(in_array($dets['roundID'], $idsArray)){
//apply CSS
//display details here
}
else{
//display details here
}
}
Note: You should stop using mysql_* now. Its highly recommended by experts to use mysqli_* instead
I will take your example of $total_rounds = 16 my $score_count would be 6.
$total_rounds = 16;
$score_count = 6 // comes from the if-else loop you already have
// now we loop over the result
// the css is applied to every odd result, until $score_count is not 0
$counter = 0;
while( ( $data = mysql_fetch_assoc( $result4 ) ) !== false ) {
if( ( $counter % 2 ) && $score_count ) {
echo $data['date']; // apply your css here
} else {
echo $data['date'];
}
$counter++;
$score_count--;
}
Hope this helps.

Categories