Why use always while loops to fetch mysql results? - php

The funny thing is that I can't find a good Explanation for this question.
Is there any disadvantage when I don't use a "while-loop" to fetch a mysql result?
Everywhere I see this line of code:
while ($row = mysql_fetch_array($result)) {
// do something with $row
}
I'm not sure that I have ever seen code that used a foreach-loop to fetch mysql results.
So is there anything wrong with other Loops or is the while-loop the only Loop that is easy and simple to use for it?
I guess there is no performance problem for regular uses with while-loops or foreach-loops with 100-1000 resultsets, isn't it?

I guess the answer is that :
"Foreach" is used when we want to loop through a code for each element in an array.(It handles each element inan array)
"For" is used when we want to loop through a block of code a specified number of times.
"While" : is used to loop through a block of code as long as a special condition is true .
I hope everything is clear for more info you may visit this website : http://www.tutorialspoint.com/php/php_loop_types.htm

Related

while loop runs only in the first iteration of foreach loop

I am trying to loop while inside for loop but the while loop is only iterating in the first iteration of for loop after I only get whatever is outside while loop to work but while stay here my code any help will be great . Thanks
if(mysqli_affected_rows($obj->conn)>0){
foreach ($dateGroup as $value) {
while($fetchdata=mysqli_fetch_array($selectdata))
{
echo 'executing while <br>';
}
echo "<b>executing foreach</b><br>";
}
}
First of all - you should reeeeeally try spliting your questions into more understandable fashion - using more sentences, commas, question marks, etc. It could be really hard to understand your problem.
Secondly - you should actually ask a question, not just ask for help with a code that might contain who-knows-what specifics.
In your case the expression inside the while loop parenthesis fetches the data once and there is no more fetching of data afterwards. This is why your while loops executes just once. You should rethink your design here, code proposal, in my opinion are not relevant.

Why "while" loop is always used to iterate through mysql_fecth_array() function result?

Why don't people use for ,foreach or do..while() and why omit increment counter in while?
`<?php while ( $fa = mysql_fetch_array($sel1) )//uesd mysql_fetch_array() function in while loop
{
echo $fa['cid'];//display client id
}
// while Syntax in w3school give to used this
$x = 1;
while($x <= 5) {
echo "The number is: $x";
$x++;
}
?>//show why we don't used mysql_fecth_array() like this
This is kind of dated information. In one way you're asking a question that is just accepted along the community. It is understood better that while I have information to show ... do something. You generally wouldn't say foreach of these items ... do something though you could. However, the other problem is mysql_fetch_array returns FALSE if there are no more rows. This would not work in a foreach because it is not an array. A for would also fail because to check for the finishing of a for you have to go to some point and end.. FALSE is not a valid point of check (that I have ever tried or used).
#Michael Berkowski Adds:
As of PHP 5.4+, the mysqli_result class does have Iterator support, meaning you can do $result = mysqli_query(...); and subsequently foreach ($result as $row) {...} and it will fetch associative arrays
Though this isn't to be said the most commonly used form which is why we have the question.
You could do...while but why would you. You don't have most the information that you're going to need from the fetch array.
While is accepted and generally better. Doesn't fail and has a fall back if the mysql fails any way.
Lastly... don't use mysql_* anymore. Switch to mysqli_*. Safer.. smarter.. better.
You can perfectly use any other loop to get the query results. The reason why people mostly use while loop is because it simply is the easiest way. The reason for that is that without any extra line of code we don't know how many rows were returned and so we don't know how many times we have to iterate to get all the rows from the result. Everytime mysql_fetch_array() is executed, it gives us the next row of data and when it runs out of rows it returns false. So using while loop we basically say: While there is still a new row, we take the data from it, fetch the next row and when we run out of rows, we stop.
You can accomplish the same with for loop for example. It's just not that straightforward.
Using for loop to iterate mysql_fetch_array() :
$r = mysql_query($query);
$num_rows = mysql_num_rows($r);
for($i = 0; $i < $num_rows; $i++) {
echo mysql_fetch_array()[$id];
}
Other choice would be to place an if statement inside the for loop to check if there are any new rows, when not, we can exit the for loop.
Using the while loop we kinda combine the loop and the if statement.

Using Same Variable in Multiple PHP `while` Loops

I have a PHP page with multiple mysql_query instances. Almost every one uses a while loop to retrieve multiple rows of data.
As I keep a snippet of this often used code, and the example I was taught with, used the variable $row, I have multiple instances of the following on my page:
while ($row = mysql_fetch_assoc($foo_data)) {
$barArray[] = $row['barValue'];
}
I even have an instance of $row = mysql_fetch_assoc($foo_data) without a while loop.
I'm wondering if the multiple uses of $row as a variable on a single page, is all right?
The PHP is functioning fine, but I always want to be sure that my code is proper and conforms to standard rules.
Thank you.
yes, it's all right.
it's all right to use the same spoon when you're eating soup.
Yes that is fine. but if you try:
var_dump($row);
at the end of your code -- it will only return that last value of $row
Yup, not a problem at all.
Just like always using $i as your count in a for loop, you can repeatedly use $row to no ill effect.

Reset MySqli pointer?

I'm struggling a bit with resetting a pointer. I want to do this because I'm going to use the same query twice in the same script. As far as I can work out I can do this with resetting the pointer after I've looped trough the fetched array. If there is a better way to do this, I'd love to hear it.
Anyway, this is what I got.
$getEvent = $connection->prepare("SELECT * BLABLA FROM BLABLA");
$getEvent->bind_param("i", $eventID);
$getEvent->execute();
$getEvent->bind_result($eventMember, $eventStaff, $eventMemberID, $eventMemberSuper);
while($getEvent->fetch())
{
// Do stuff
}
// Then bunch of code, before finally another
//$getEvent->execute(); //Script doesn't work without this and next line
//$getEvent->bind_result($eventMember, $eventStaff, $eventMemberID, $eventMemberSuper);
while($getEvent->fetch())
{
// Do other stuff
}
I've tried with $getEvent->data_seek(0); but no luck. The script only works if I redeclare $getEvent->bind_result. Thanks in advance for any replies.
This places unnecessary extra strain on the database server. Rather than rewind and reuse the result set, store the whole thing in an array to begin with. You may then use it as many times and different ways as you like in the PHP application code.
Update Fixed code so it should work with MySQLi rather than PDO. Also, made the results into an associative array.
$results = array();
while($getEvent->fetch())
{
$results[] = array('eventMember'=>$eventMember, 'eventStaff'=>$eventStaff, 'eventMemberID'=>$eventMemberID, 'eventMemberSuper'=>$eventMemberSuper);
}
// Now use $results however you need to.

How can i find out if I am at the last row in a data set?

I would appreciate some help on this, I have a result set which I am trying to work with. The result contains 2 fields and any number of rows.
In calling fetch_row() how can you tell if the method has got to the last row?
I am iterating through the rows using:
while(list($className, $classID) = $result->fetch_row()) {
echo "<tr><td>$className has ID $classID.</td></tr>"
// Here, if the loop is for the last time I need to allow some extra code to run
// echo "<tr><td>Last Item.</td></tr>"
}
I was thinking about having an incremental counter in the while loop which compares the row to num_rows but was thinking that there must be a slicker was of telling if you have reached the last row
Any advice much appreciated.
Many Thanks
ShaunMc
I was thinking about having an incremental counter in the while loop which compares the row to num_rows but was thinking that there must be a slicker was of telling if you have reached the last row
Nope, I think that is actually the only way to do this, regardless of which DB wrapper you're using (I assume it's PDO.)
It's a shame really: PHP should have something like this built in, at least in foreach constructs. But it doesn't.
fetch_row() returns null when it hits the end of the result set.
http://php.net/manual/en/mysqli-result.fetch-row.php
Or am I missing something.

Categories