Invalid argument for foreach - php

there is no issue with this query, as when I use print_r it prints out three different arrays, Im just wondering what Im missing here to get this foreach working, as at the moment Im getting an error...
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\myshop\admin\account_list.php on line 11
<?php
$account_list = "SELECT * FROM accounts";
$query = $connect->query($account_list);
while ($final_result = $query->fetch_array(MYSQLI_ASSOC)) {
// echo '<pre>';
// print_r($final_result);
// echo '</pre>';
}
echo '<table><tbody>';
foreach ($final_result as $result) {
echo '<tr><td>'.$result['id'].'</td>
<td>'.$result['firstname'].'</td>
<td>'.$result['lastname'].'</td>
<td>'.$result['email'].'</td>
<td>'.$result['address'].'</td>';
}
echo '</body></table>';
?>

As it is, you're not calling foreach until after the query has completed, at which time $final_result is FALSE. foreach (false as $result) is, indeed, invalid.
You'll want to combine the two loops:
$account_list = "SELECT * FROM accounts";
$query = $connect->query($account_list);
echo '<table><tbody>';
$final_result = false;
while ($result = $query->fetch_array(MYSQLI_ASSOC)) {
// echo '<pre>';
// print_r($final_result);
// echo '</pre>';
$final_result = $result;
echo '<tr><td>'.$result['id'].'</td>
<td>'.$result['firstname'].'</td>
<td>'.$result['lastname'].'</td>
<td>'.$result['email'].'</td>
<td>'.$result['address'].'</td>';
}
echo '</body></table>';

$final_result is not an array, but an element of the array, instead of while just write-
$final_result = $query->fetch_all(MYSQLI_ASSOC);

Related

Filtering an array with foreach and for loop

I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}

get COUNT(*) from mysql_magic

The following code retrieve the result from queries. Usually, I ask for SELECT... and I get a two-dimensional array but this time I need to get count from a table.
if(isset($_GET['query']))
{
$results = mysql_magic($_GET['query']);
$response = array();
//ERROR : Invalid argument supplied for foreach()
foreach($results as &$row)
{
$rowArray = array();
foreach($row as &$column)
{
$rowArray[] = $column;
}
$response[] = $rowArray;
}
$jsonData = json_encode($results);
}
This is a part of the function mysql_magic. In most cases, it returns mysql_fetch_all($req_result). In this case, it returns a row.
else if (startsWith($req_sql, 'select count(*)'))
{
$line = mysql_fetch_row($req_result);
return $line[0];
}
Why do I get an error "Invalid argument supplied for foreach()" since my result, a count, contains one row and one column?
I think that you are using mysql_magic($_GET['query']) should be mysql_query($_GET['query']). I see no reference in the code for a $_GET case. So $results is undefined due to php error?
if(isset($_GET['query']))
{
$results = mysql_query($_GET['query']);
$response = array();
//ERROR : Invalid argument supplied for foreach()
foreach($results as &$row)
{
$rowArray = array();
foreach($row as &$column)
{
$rowArray[] = $column;
}
$response[] = $rowArray;
}
$jsonData = json_encode($results);
}

how do I look an array to extract data

Hi all Im trying to query a database and store the results ($searchResults[]) as an array :
<?php
if(isset($_POST['indexSearchSubmit']))
{
foreach($_POST['industryList'] as $selected)
{
$_POST['industryList'] = $selected;
$locationListResults = $_POST['locationList'];
$results = mysqli_query($con,"SELECT * FROM currentListings
WHERE location = '$locationListResults' AND industry = '$selected'");
$searchResults = array();
while($row = mysqli_fetch_array($results))
{
$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];
}
}
mysqli_close($con);
}
?>
the problem im getting is when I try to echo the result:
<?php
echo $searchResults[0];
?>
its only bringing back 1 result not displaying all the results in the arrray as i want it to.
Could anybody please point out what it is im doing wrong.
Any help would be greatly appreciated
Do like this
<?php
print_r($searchResults); // Prints all array elements
?>
Alternatively, you can make use of a for loop to echo all elements too..
foreach($searchResults as $k=>$v)
{
echo $v;
echo "<br>";
}
Your code puts your data into 1D array. You probably want sth else so instead of this:
$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];
do this:
$tmp = array();
$tmp['industry'] = $row['industry'];
$tmp['location'] = $row['location'];
$tmp['title'] = $row['title'];
$tmp['description'] = $row['description'];
$searchResults[] = $tmp;
or just this (thanks to Barmar):
$searchResults[] = $row;
This way you store your data as 2D array. So every row you obtain remains in one subarray.
To print the row (which is now in 2D array) iterate over subarrayw:
foreach($one_of_searchResult_rows as $k => $v)
{
// do whatever you need with $k and $v
}
I think you want a 2d array. Try this code snippet :
$searchResults = array();
while($row = mysqli_fetch_array($results))
{
array_push($searchResults,$row);
}
This should push each row as an associative array in every cell of your final searchResuts array. You could then access the values like:
echo $searchResults[0]['industry']; //and so on
echo $searchResults[0]; //Should print out the first match/row of the sql result
Lets make it simple :
$serach_result=mysqli_fetch_all ($result,MYSQLI_NUM);
//you should use print_r while trying to print an array
print_r($search_result[0]);
Reference : mysqli_fetch_all

output specific array key for each result

i have a search engine for my page. as a result i would like to ouput the array key for each result.
so i have this code:
$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found
if (!empty($errors){
foreach ($results as $result){
echo "this is result: "
.$result['key']; //thought would be the solution, its not.
}
} else {
foreach ($errors as $error){
$error;
}
}
i also tried using a counter like:
$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found
$counter = 0;
if (!empty($errors){
foreach ($results as $result){
$counter++;
echo "this is result: "
.$counter;
}
} else {
foreach ($errors as $error){
$error;
}
}
what doesnt work as i thought and is still not that professional.
so if there is someone who could tell me how to solve this i really would appreciate. thanks a lot.
foreach ($results as $key => $result) {
echo 'this is result: ' . $key;
}
The current key will be assigned to $key and the value for that property will be assigned to $result
http://php.net/manual/en/control-structures.foreach.php
edit
In response to your comments, I think this is what you're trying to achieve:-
$i=0;
foreach($results as $result) {
echo 'this is result: ' . ++$i;
}
foreach($arr as $key=>$val){
//do something with key and value
}
Here in code you can check first if $results array is not empty because sometime due to empty $results array foreach generates error
/*Check if $results array is empty or not*/
if(!empty($results)){
foreach ($results as $key=>$result){
/*result you want to show here according conditions*/
}
}

Array of associative arrays in PHP

I have a function to use but I don't know the content of this function. The only thing I know is that the function returns an array of associative arrays and the keys for the arrays. The data that the function returns come from a database. Can you help in how to read the data from this array? I am confused with the arrays. For now I am doing this:
$array = myfunction($var);
if(!empty($array))
{
while($row = mysql_fetch_array($array))
{
print"$row[elem1]
$row[elem2]";
}
}
I take the error: Warning: mysql_fetch_array() expects parameter 1 to be resource, array given in... I know that something is missing, but I till now I can't fix it.
If the function is returning an array then why are you using it in mysql_fetch_array. It is useless. Instead use this
foreach($array as $key => $value){
echo $key;
echo '<br>';
echo $value;
}
This will print the whole array.
Or a short method is
echo '<pre>';
print_r($array);
echo '</pre>';
Something like -
$array = myfunction($var);
foreach($array as $key => $row) {
print"{$row['elem1']} {$row['elem2']}";
}
You have to pass Resource Identifier to mysql_fetch_array() function.
Something like:
$sql = mysql_query('SELECT * FROM `table`');
if(!empty($array)) {
while($row = mysql_fetch_array($array)) {
print"$row[elem1]
$row[elem2]";
}
}
The error is correct .. the issue is not associative arrays in php but you are not using a valid mysql resource
Please see http://php.net/manual/en/function.mysql-fetch-array.php for documentation
Examples
$mysqli = new mysqli("localhost","root","","test");
$result = $mysqli->query("SELECT * FROM test");
$row = array() ;
echo "<pre>" ;
if($result->num_rows > 0)
{
while($row = $result->fetch_array(MYSQLI_NUM))
{
print implode (",", $row) . PHP_EOL;
}
}
Or
$array = myfunction($var);
if(!empty($array))
{
foreach($array as $key => $row)
{
if(is_array($row))
{
print implode (",", $row) . PHP_EOL;
}
else
{
print $row . PHP_EOL ;
}
}
}

Categories