I'm trying to fetch data and display it via foreach loop but it's not working giving argument error but when i try this with while loop it's work fine. so my question is that why i cannot fetch data using mysqli_fetch_array with foreach why it's only possible with while loop
// While
while($row = mysqli_fetch_row($result))
{
var_dump($row); echo "<hr />";
}
// Foreach
foreach(mysqli_fetch_array($result) as $row)
{
var_dump($row); echo "<hr />";
}
You can't use foreach for mysqli_fetch_array directly.
Foreach is a loop using for an exist array, to loop through each its item
You can use like below
$result = array();
while($row = mysqli_fetch_array($result)) {
$result[] = $row;
}
foreach($result as $row) {
var_dump($row);
echo "<hr />";
}
Because mysqli_fetch_array as comes from it's name - fetches one row of your result as array.
So, foreach(mysqli_fetch_array($result) as $row) means
Fetch one row and iterate over this row.
While while($row = mysqli_fetch_row($result)) means
Do fetching rows until there's nothing to fetch.
And when there's nothing to fetch while-condition is false and the loop breaks.
Info about while-loop and foreach-loop
Related
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...
What would the benefits be of storing db values into an array and then looping through the array vs just using a while loop?
Outputting db results to an array:
$records = array();
if($results = $db->query("SELECT name, address FROM town")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
Loop through array:
foreach($records as $r) {
$r->name;
}
VS a simple While loop:
if($result = $db->query("SELECT name, address FROM town")) {
if($count = $result->num_rows) {
while($row = $result->fetch_object()) {
echo $row->name, ' ', $row->address, '<br />';
}
$result->free();
}
}
Just a while loop and printing the result is easy and fast, but in certain times you want to do more then just print the array and then it becomes handy if you already work with arrays.
The most common use for this is freeing the resultset, allowing you to perform other db queries (updates, inserts...) before actually making any use of the results you got in the first place.
$result = mysql_query($strSql);
foreach($bestmatch_array as $restaurant)
{
while($row = mysql_fetch_array($result))
{
if($restaurant == $row[0])
{
$value = $row[1];
}
}
}
What I am trying to do is sort the result of array formed by query according to the values stored in $bestmatch array.
I don't know what I am doing wrong but the 4th line just seems to run once. Please help guys. Thanx in advance.
php mysql_fetch_array() not working as expected
Your expectation is not right.
foreach($bestmatch_array as $restaurant)
{
// This loop will only run for first iteration of your foreach.
while($row = mysql_fetch_array($result))
{
}
// everything has been fetched by now.
}
That is a logically incorrect sequence.
You expect your inner loop to be called over and over again as many times as you have the outer loop run but record fetch does not work like that. For outer loop's first run all the rows in $result will be fetched and since you do not reset the counter after your while loop that means after the first run there will be no more rows for the next run.
Solution? Fetch the row from mysql first then use a simple in_array call to check whether that restaurant is there in your array.
$result = mysql_query($strSql);
while($row = mysql_fetch_array($result))
{
$name=$row[0];
if(in_array($name,$bestmatch_array))
$value=$name;
}
Store the results of the query in the array first:
$result = mysql_query($strSql);
$results_row = array();
while($row = mysql_fetch_array($result))
{
$results_row[] = array($row[0],$row[1]);
}
foreach($bestmatch_array as $restaurant)
{
foreach ($results_row as $key => $value)
{
if($restaurant == $results_row[$key][0])
{
$value = $results_row[$key][1];
}
}
}
I'm transitioning over to PDO prepared statements, and I'm having trouble with the syntax for a basic SELECT query with a WHILE statement.
The foreach statement below echos the correct results, but the PDO::FETCH_ASSOC query is skipping the 1rst result that's returned (so it always echo's one result less than it should).
PDO::FETCH_ASSOC
$stmt = $conn->prepare("SELECT * FROM products");
$stmt->execute();
$row = $stmt->fetch();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['product_name'].' '.$row['price'].' '.$row['color'], "<br />";
}
foreach
foreach($conn->query('SELECT * FROM products') as $row) {
echo $row['product_name'].' '.$row['price'].' '.$row['color'], "<br />";
}
You already fetched the first row before the while loop $row = $stmt->fetch();. If you remove this line, it will work as expected.
Since the while loop will overwrite $row on each iteration, it looks like you start with the second row, but what happens is the value of $row at the first while loop iteration is overwritten.
To have the loop work the way you have written, you would need to use a do-while construct:
$row = $stmt->fetch();
do {
echo $row['product_name'].' '.$row['price'].' '.$row['color'], "<br />";
} while($row = $stmt->fetch(PDO::FETCH_ASSOC));
Here the value of $row will be printed first, before it is overwritten by the while condition.
In this particular case I don't want to echo anything when there aren't any results
If that's the case, then check to see if your query returned any results first. Here I'm being explicit in the check, because if you removed the outer if, your while loop would still follow your intentions - that is, it won't echo anything if there aren't any results.
However, it is always good to have clear intent in your code:
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['product_name'].' '.$row['price'].' '.$row['color'], "<br />";
}
}
Do not do $row = $stmt->fetch() before loop.
I have problem with Mysql query. I wrote this code
enter code here
$result = mysql_query("SELECT * FROM description");
while ($row = mysql_fetch_array($result)){
$data[] = $row;
foreach ($data as $row){
echo $row['name'];
}
}
enter code here
and my output is:
First description
First description
Second description
First description
Second description
Third description
I have 3 description in db (first, second, third) and I don't have a clue why he give me something like this.
Does anyone knows what is wrong?
You need to move this to after your while loop:
foreach ($data as $row) {
echo $row['name'];
}
First you get all your rows in your $data variable, and only then you start echoing them out.
mysql_fetch_array() returns a dual array: integer AND string keyed. If you'd done:
while ($row = mysql_fetch_array($result)){
var_dump($row);
}
You'd see both keys. Try using mysql_fetch_assoc() instead, which returns the string-keyed version only.
your foreach loop is inside of your while loop. move it outside and try.
$result = mysql_query("SELECT * FROM description");
while ($row = mysql_fetch_array($result)){
$data[] = $row;
}
foreach ($data as $row){
echo $row['name'];
}