While loop with assignment operator - php

I can't seem to figure out how this loop works in PHP:
$people = array();
while($row = $result->fetch_assoc())
$people[] = $row;
It seems as though the loop would just keep going, infinitely. But, it doesn't How exactly does this work? Can someone explain it to me step-by-step? I'm guessing that the while loop could also be written like this:
while(($row = $result->fetch_assoc()) == true)

The fetch_assoc fetches one result row at a time and stores it in $row. Since this is in a loop, you are fetching until you run out of rows
In the loop you are essentially pushing the $row value into a $people array

Your code:
$people = array();
while($row = $result->fetch_assoc())
$people[] = $row;
Example how its works (MySQL):
$people = array();
$result = mysql_query($query);
$rows_count = mysql_num_rows($result);
for ($i = $rows_count - 1; $i >= 0; $i--) {
mysql_data_seek($result, $i);
$people[] = mysql_fetch_assoc($result);
}
How U see first option is more compact.

fetch_assoc will return false either upon an error or when the cursor for the fetch hits the end of all the rows and no more rows can be fetched, so it will return false.
Every time you fetch for the query, a cursor keeps track of the last returned row and will continue to keep track ultimately till you finish reading all rows.
Edit: Sorry I was thinking about PDO and not mysqli, however it should be about the same thing.

Related

Understanding mysqli_fetch_array()

Is there a way to make the code below cleaner?
I wanted to access the rows of $query4week like this: $query4week[0].
But mysqli_query() returns an Object on which I don't know how to access its particular rows. So, using fetch_array and a for loop I decided to create my own index.
$sql2 = "SELECT * FROM meals ORDER BY RAND() LIMIT 7";
$query4week = mysqli_query($con, $sql2) or die(mysqli_error($con));
for ($i = 0; $result = mysqli_fetch_array($query4week, MYSQLI_ASSOC); $i++)
{
$meal4week[$i] = $result['meal'];
}
I am still learning PHP and yet quite weak with OOP topics, please be patient :-)
Do it in this way
$i = 0;
while ($result = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
$meal4week[$i] = $result['meal'];
$i++;
}
should work.
You shouldn't need a for loop if your fetching an associative array.
$i = 0;
while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
$meal4week[$i] = $row['meal'];
$i++;
}
There are already some perfectly reasonable answers here, but this is a little long for a comment. If all you are creating is a numerically indexed array starting with index 0, you don't need to explicitly define the index.
while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC)) {
$meal4week[] = $row['meal'];
}
should work just fine. No $i necessary.
mysqli_query returns you a resource which represents the query result. You need to use the mysql_fetch_* functions to iterate over the result row by row. So yes, you need some kind of loop, if you are interested in more than the first row.

While loop showing only one result

I want to show string outside while loop, but it only shows one result.
while($row = $result->fetch_assoc()) {
$myarr = array();
}
echo $myarr;
This shows only one result but I need all the results outside the while loop.
Could you please help me how is this possible?
I am not sure if you want the whole row returned from the query or just a single field.
If its the whole row then try
$myarr = array(); // initialize
while($row = $result->fetch_assoc()) {
$myarr[] = $row;
}
print_r($myarr);
This will give you an array containing n row arrays.
Problem :
You are just assigning the result one after again
$myarr = array();
Here, It means you're assigning the array() again and again, which replaces the old value
Solution / What You should do
1. You can assign it to an Array (Good Approach)
while($row = $result->fetch_assoc()) {
$myarr[] = $row['yourdbitem']; // or $row if you want whole row
}
print_r($myarr);
2. You can concat in each iteration (Bad Approach)
$somevariable = '';
while($row = $result->fetch_assoc()) {
$somevariable .= $row['yourdbitem']; // or $row if you want whole row
}
echo $somevariable
Note :
I have given good and bad approach to updating what you should do and what you should not do :)

how to check, if there are still rows left from fetch_assoc loop?

I loop trough the rows with this code:
while ($row = $result->fetch_assoc()) {
//...
}
But how is it possible before the mysqli_fetch_assoc to check if there will be a next record, or not? I mean, like: $result->hasNext()
Check the total number of returned rows using $mysqli->num_rows, then compare it to a counter in your loop that you increment with each loop iteration.
$row_cnt = $result->num_rows;
$loop_ct = 0;
while($row = $result->fetch_assoc()) {
if(++$loop_ct < $row_cnt) {
//do something
}
}
I prefer working efficiently and don't write extra code if it isn't needed. The following will work just fine:
$cnt = $result->num_rows;
while($row = $result->fetch_assoc()){
//....
$cnt--;
if($cnt == x){ //Where x is the number you want
//....
}
}
You're doing a while loop until you don't have any rows left, so the question is do you really need a test or do you just run the code you want at the end of your loop? If you need to test inside whether there will be a next row, you could do this:
$row = $result->fetch_assoc();
while (1) {
...
if (!$row = $result->fetch_assoc()) {
// No next row
break;
}
}
Which is pretty similar to what you're doing now.
Consider the code you posted
while ($row = $result->fetch_assoc()) {
//...
}
It is already doing that. check out the docs for mysqli_result::fetch_assoc, the while loop will break if $result->fetch_assoc() returns NULL. You don't need to manually check anything.
Either you can go with #McWayWeb or you can try this function mysqli_next_result().
Read it's manual here:- http://php.net/manual/en/mysqli.next-result.php

Looping Through SQL Results in PHP - Not getting Entire Array

I'm probably missing something easy, but I seem to be blocked here... I have a MySQL database with two tables and each table has several rows. So the goal is to query the database and display the results in a table, so I start like so:
$query = "SELECT name, email, phone FROM users";
Then I have this PHP code:
$result = mysql_query($query);
Then, I use this to get array:
$row = mysql_fetch_array($result);
At this point, I thought I could simply loop through the $row array and display results in a table. I already have a function to do the looping and displaying of the table, but unfortunately the array seems to be incomplete before it even gets to the function.
To troubleshoot this I use this:
for ($i = 0; $i < count($row); $i++) {
echo $row[$i] . " ";
}
At this point, I only get the first row in the database, and there are 3 others that aren't displaying. Any assistance is much appreciated.
You need to use the following because if you call mysql_fetch_array outside of the loop, you're only returning an array of all the elements in the first row. By setting row to a new row returned by mysql_fetch_array each time the loop goes through, you will iterate through each row instead of whats actually inside the row.
while($row = mysql_fetch_array($result))
{
// This will loop through each row, now use your loop here
}
But the good way is to iterate through each row, as you have only three columns
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['email']." ";
}
One common way to loop through results is something like this:
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
// do stuff with $row
}
Check out the examples and comments on PHP.net. You can find everything you need to know there.

How fetch 1 more but get rid of it later?

Currently I fetch rows with the help of mysql_fetch_array() (and the LIMIT/OFFSET) (ie. while ($row = mysql_fetch_array($res)) { ... }); but the last row is not needed as it was to be fetched in order to make sure there is at least one more row left - it is not for display.
You can simply get the number of rows before this loop:
select count(*) from <your_table> WHERE <your_condition>;
Then, you can exclude the last record within the loop using a counter.
Is this what you want??
You should not mix presentation with logic anyway. Fetch all the rows in an array:
$rows = array();
while ($row = mysql_fetch_array($res)) {
$rows[] = $row;
}
and delete the last one:
array_pop($rows);
Or just set LIMIT to get one less of that is possible.
Update:
Here is another possibility using a for loop and mysql_num_rows:
for($i = mysql_num_rows($res) - 1; $i--; $row = mysql_fetch_array($res))
but the first one is more readable imo.

Categories