PHP assign result from nested query into array - php

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

Related

PHP run query off each array variable and return results in table

I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.

Sort array by rule made of mysql select

Hello everyone I have really chalenging task I have to sort an array by condition with mysql select or by another array. Imagine something like that
$arrayINeedToSort = array(5,4,7,96,1,0,55);
// Dont know if it is important cause of next step
sort($arrayINeedToSort);
$arrayToCheckDuplicData = array();
foreach($arrayINeedToSort as $aid)
{
$sql = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId = $aid ");
$num = mysql_num_rows($sql);
if($num)
{
echo $aid;
}
else
{
// skip this id cause it is not in array but i would like to push at the end of an array again sorted
if(in_array($aid,$arrayToCheckDuplicData))
{
echo $aid;
}
else
{
$arrayINeedToSort[] = $aid;
}
$arrayToCheckDuplicData[] = $aid;
}
}
Thats my idea, pushing array values to the end of acutal array with another simple array check but i am open to different/better ideas.
UPDATE //////////////////////////////////////////////
I need to see all ids so i cant skip them and I need them sorted.
TO BE MORE SPECIFIC i would liek to have input like this
1,4,96 (of values which are in database ) 0,5,7,55 (of values which are not in databse) at the end array will look like this
$outputSortedArray(1,4,96,0,5,7,55);
Could you please be more specific in what you want. On what is the input and what you want in your output.
If you need to sort the array $arrayINeedToSort then use sort function.
Give an example of the input and output array. Also the table with condition you wanted to check.
Check the following code and verify if this is what you want:
`
$arrayINeedToSort = array(5,4,7,96,1,0,55);
$in_cond = implode(",", $arrayINeedToSort);
$arrayToCheckDuplicData = array();
$result = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId IN (" . $in_cond . ") ORDER BY arrayValueId ASC");
$num = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if (in_array($row["arrayValueId"], $arrayINeedToSort)) {
echo $row["arrayValueId"];
}
else {
if (in_array($row["arrayValueId"], $arrayToCheckDuplicData)) {
echo $row["arrayValueId"];
}
$arrayToCheckDuplicData[] = $row["arrayValueId"];
}
}
`
You can use php array sorting functions: http://www.php.net/manual/en/array.sorting.php
There is also a function called array_unique, which is delete multiple values from an array.
If you want to sort the array in the MySQL query, use "ORDER BY ASC/DESC".

I can't get the value of a query outside the loop

I'm using PHP and I do a mysql query and I save the result of this query in an array. Then, I use a loop and into the loop i do another mysql query using the values of the array in the where clause. It's right but if I try to get the result of the query outside the loop I can't.
Here an example code
$result=$mysqli->query("SELECT code FROM referee");
$i=0;
$arcode=array();
while($row=$result->fetch_array()){
$arcode[$i]=$row["code"];
$i++;
}
for($j=0;$j<sizeof($arcode);$j++){
$result2=$mysqli->query("SELECT code, time FROM match where referee_code IN ($arcode[$j])");
}
/*Here I can't get the result values*/
$matcode=array();
$hour=array();
$k=0;
while($row2=$result2->fetch_array()){
$matcode[$k]=$row2["code"];
$hour[$k]=$row2["time"];
}
If I put all in the same loop I get the result repeated (This code is one example of all my code but the idea is the same in the rest).
You are overwriting the result set values into $result2.
The correct method would be something like:
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
while ($row2 = $result2->fetch_array())
{
$matcode[] = $row2["code"];
$hour[] = $row2["time"];
}
You may change the index values according to the way you want the array to look like.
Also match is a reserved word. So you would have to enclose it in backticks.
If you want to print complete data then try this :
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
$completeData=array();
while ($row2 = $result2->fetch_array())
{
$completeData[] = $row2;
}
print_r($completeData);
Don forget to accept answer if it helps :)

How do I insert values into an multidimensional-array, then show them?

I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Categories