How to change "while" loop to a "foreach" loop - php

I would like to ask a question about "foreach loop" in PHP. Towards the bottom of the code below, the "while" loop accesses elements from an array individually. How can I rewrite the BODY of the while loop using a "foreach" loop?
<?php
require_once('MDB2.php');
$db = MDB2::connect("mysql://mk:mk#shark.company.com/mk");
if(PEAR::iserror($db)) die($db->getMessage());
$sql = "SELECT courses.ID,courses.Name,staff.Name
FROM courses,staff
WHERE courses.Coordinator=staff.id
and courses.ID = \"$course\"";
$q = $db->query($sql);
if(PEAR::iserror($q)) die($q->getMessage());
while($row = $q->fetchRow()){
echo "<tr><td>$row[0]</td>\n";
echo "<td>$row[1]</td>\n";
echo "<td>$row[2]</td></tr>\n";
}
}
?>
</table>
</body></html>

Perhaps:
echo "<tr>";
foreach( $row as $field => $value )
{
echo "<td> \"$value\" </td>";
}
echo "</tr>";

As Poitr Olaszewski commented. You will need to fetch the whole collection to be able to itterate through using foreach().
That means instead of the whole while($row...., you'd do something like this:
$data = $q->fetchAll();
foreach($data as $key => $val) {
// do what you need to here....
}
More reading -> Documentation for fetchAll() for MDB2.php

Related

How to copy an associative array inside another associative array in PHP

Can anyone tell me how to store an array of associative arrays? I thought this code would work, but it's not. I tried researching it but couldn't find an answer.
foreach($rows as $row) {
// Some SQL...
if ($stmt->execute()) {
while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['NestedResults'][] = $row2;
}
}
}
foreach ($rows as $row) {
foreach ($row['NestedResults'] as $results) {
echo $results['Item'] . '<br>';
}
}
PS: I know I shouldn't loop SQL statements like that, but it's a special case.
In your first foreach loop, you need to pass the $row variable by reference, otherwise you are just modifying a copy of the element from $rows stored in $row:
foreach($rows as &$row)
do you think it is workable to put the second loop inside the first one as below?
$row['NestedResults'][] = $row2;
foreach ($row['NestedResults'] as $results) {
echo $results['Item'] . '<br>';
}
not 100% sure...

Obtaining data from query in multidimensional array

I have spent a lot of time trying to find ways to do the following, and have researched as much as I can but am still stuck.
I have a table 'pool_a' that at the minute has 2 columns - team_id and team_name.
I need to echo the id and the name into a nested foreach loop.
Now I can do this if I am just worried about the name, but now my query includes the ID too, I can't work out how to get both bits of data for each row in my table.
Here's how I get it to work with team_name...
for ($i=0;$i<$num;$i++) {
$team=mysql_result($result,$i,'team_name');
$team_names[$i] = $team;
echo $team . "<br>";
}
foreach ($team_names as $team) {
foreach ($team_names as $opposition) {
if ($team != $opposition) {
echo "<tr><td>" . $team . "<td><input type=\"text\"<td>versus<td><input type=\"text\">" . $opposition . "</tr>";
}
}
}
This is great, and outputs the correct fixture list and with input boxes for scores, but I need to add a hidden data input with team_id as the value. For example:
Here is what I have so far. Note that I have been learning about PDO's and new 5.5 techniques, so you will notice my style of code will be different in the next snippet.
require_once "pdo_enl_connect.php";
$database=dbNB_connect();
$query=$database->query ("SELECT team_id, team_name from pool_a");
while ($row = $query->fetch(PDO::FETCH_NUM)) {
printf ("%s %s<br>", $row[0], $row[1]);
$teams=array($row[0], $row[1]);
}
foreach ($teams as $key=>$value) {
echo "$key and $value<br>";
}
$database=NULL;
The output I get for the foreach loop is
0 and 5
1 and Silhouettes //silhouettes being the last team in the table.
ANy help would be much appreciated, and please let me know if I can edit my question to make it clearer in any way.
Thanks
Your while loop should look like this:
$teams = array();
while ($row = $query->fetch(PDO::FETCH_NUM)) {
// $row and array($row[0], $row[1]) are the same here
$teams[] = $row;
}
You need to initialize $team = array(); before your loop.
Then add your tuple to the teams array by doing either array_push($teams, array($row[0], $row[1])); or $teams []= array($row[0], $row[1]);`

running a sql query with array elements

what I am trying to do is extract elements of an array and running an sql query with the array element as the condition. The problem what I am facing is that the query does not return anything. The code is given below
//extracting the array elements
foreach ($t as $value) {
extract($value);
}
$sql = "SELECT * FROM daily_log where employee_log_id='$employee_log_id' AND log_date='$value'</br>";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['in_time'];
echo $row['out_time'];
The echo $row['in_time'] and echo $row['out_time']; does not show anything.
Can anybody help me to figure out what the problem is
Thanks in advance.
The problem is your sql query code is outside the foreach loop. The $value variable doesn't exist in that scope.
Try this:
foreach ($t as $value) {
extract($value);
$sql = "SELECT * FROM daily_log where employee_log_id='$employee_log_id' AND log_date='$value'</br>";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['in_time'];
echo $row['out_time'];
}
EDIT:
But I can't understand what you are trying to do. I think you either need the extract() function or the foreach loop. Also, why is there a </br> html tag in your sql query string?
Do you want something like this?
foreach ($t as $key -> $value) {
$sql = "SELECT * FROM daily_log where employee_log_id='$key' AND log_date='$value'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['in_time'];
echo $row['out_time'];
}

Create unique single <div> element for all MySQL php results with particular value

Here is my problem. I am returning results from a mysql database and using a for loop to echo the results. Though its getting a little complicated because I am using some table data to nest inside other results. This code returns "Pablo Picasso" inside a div called "Spain", fine, but if there is "El Greco" in Spain too, then I get two "Spain" divs, rather than just the one.
So: I'd like to only return a result once for each unique value in a table column, rather than for every one.
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
foreach ($results as $row)
{
echo "<div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
$tempCountry = $row['country'];
foreach ($results as $row)
{
if ($row['country']== $tempCountry) echo "<div>artists name</div>";
}
echo "</div>";echo "</div>";
}
I'm wondering if it is the construction of the nested loop, or something else, I don't know!!! Please help
I agree with #Kalpesh that you need to order the results by country.
Right now you have multiple nested loops when all you really should need is one. Try using just one loop to go through the data. On every iteration, check the $tempCountry value to see if it different compared to the current row's country. If it is, you need to close the current <div>, open a new <div> and update the $tempCountry value. Otherwise, echo the name of the artist.
EDIT: Psuedocode added below
Retrieve data from database (the query should sort the data by country)
Initialize $tempCountry to null
Loop over every row
If $tempCountry equals this row's country
Print the artist
Else
Set $tempCountry equal to this row's Country
Close the div tag
Open a new div tag
Print the artist
Note that you do not want to close the div tag on the first time through the loop. Also, you need to close the div tag after the loop finishes.
foreach ($results as $row) {
if ($tempCountry == $row['country']) {
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
else {
$tempCountry == $row['country'];
echo "</div><div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
echo "</div>";
}
Create an empty array outside of your loop. On output push the values of $row into the array inside of your loop. Then only output if value does not already exist in the array. You can use in_array for this.
The solution I found was to nest a foreach inside another, the outer loop SELECTS with a GROUP BY.
In this example I get one outer for each country, then inside that , every person (or item) within that country (or with that column value). Really useful.
NEW CODE: SOLUTION (use GROUP BY to build outer container)
// create array to build group div
$country = mysql_query("SELECT * FROM table GROUP BY `country`");
// create array for inner contents
$result = mysql_query("SELECT * FROM table ORDER BY name");
//array for group(countries in this instance)
$countrys = array();
while ($row = mysql_fetch_assoc($country)) {
$countrys[] = $row;
}
//array for inner contents
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
$tempCountry="";
foreach ($countrys as $row)
{
$tempCountry = $row['country'];
echo "<div class=\"".$row['country']."\">";
echo $row['country'];
echo "<div class=\"Box\">";
foreach ($results as $row) {
if ($tempCountry == $row['country'])
{
echo"<div>inner contents of that group</div>";
}
}
echo "</div>";
echo "</div>";
}

PHP For Loop Printing An Array

This might seem like a really easy question but it has got me stumped lol. I am trying to print the rows received from the database. I want to store the rows inside an array and then print them using a for loop. I know that the query works however when I try to print the array elements it only prints the word array. I have tired doing it with a foreach loop and a simple for loop. If anyone can point me in the right direction would be a life saver.
Printing Php Code
<?php
$type = "FREE";
$free = getTerms($type);
echo "<p>";
for($j = 0; $j < count($free); $j++)
{
echo "start".$free[$j]."end";
}
echo "</p>";
?>
geting the rows from the database
function getTerms($type)
{
$terms = array();
$connection = mysql_open();
$query = "select terms from terms_and_con where accountType='$type' && currentTerms='YES'";
$results = mysql_query($query, $connection) or show_error("signUp.php", "", "");
while($row = mysql_fetch_array($results))
{
$terms[] = $row;
}
mysql_close($connection) or show_error("signUp.php", "", "");
return $terms;
}
Each entry in the $free array is itself an array (from $row).
Try
echo 'start', $free[$j]['terms'], 'end';
Alternatively, you may find a foreach loop more semantically appropriate
foreach ($free as $row) {
echo 'start', $row['terms'], 'end';
}
Edit: I'd advise using mysql_fetch_assoc() instead of mysql_fetch_array() if you're only going to use associative entries from $row.
the thing is function mysql_fetch_array ( as the name suggests) returns an ( in your case both associative and number) array. so $row is actually array(0 => VALUE, 'terms' => 'VALUE')
So what you are trying to echo is actually an array.
Simple fix:
replace:
$terms[] = $row;
with:
$terms[] = $row[0];

Categories