How do I loop through MySQL results easily? - php

I've been requesting MySQL results and looping through them like this:
$query = "SELECT * FROM $table";
$result = mysql_query($query);
for($i = 0; $i < mysql_num_rows($result); $i++){
echo mysql_result($result, $i, $row);
//do something else;
}
you can probably see what happens. What if a row has been deleted? What if the first item is gone? In that case, there could be 30 items in the list, but the last items index is at position 50. How do I fix this or what other systems can I use?

while($temp = mysql_fetch_assoc($result))
{
echo $temp['id']; // ID Column
}
But BTW. The mysql_num_rows returns the number of rows you fetched. If you have a row that was deleted, it wouldn't have been fetched, and therefore it wouldn't count towards the number.

Also - I believe the entire rowset is obtained at query time, rows deleted after the query is executed will still appear in your results.

Related

pdo how to check if it is 1st record that retrieve from database?

$sql3 = "SELECT member FROM levels where upline = ? AND level=1";
$q3 = $conn->prepare($sql3);
$q3->execute(array("$level2downlines"));
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
if (it is 1st record){
echo "make orange juice";
}else{
echo "make all juice";
}
}
Let say output are 3 records from database "Zac", "Michelle", Andrew". "Zac" is the 1st record get from database, how to write the "if" statement to check if the records is 1st record or not?
First off, if the order of records returned matters, you must explicitly include an ORDER BY clause in your query to specify which column to sort results on. Otherwise, the order of rows returned is technically indeterminate.
To operate differently on the first fetched row than on later rows, you may simply call fetch() outside the loop first, then loop over the remainder. Each call to PDOStatement::fetch() will advance the rowset record pointer, so the while loop will only iterate the records after the one already retrieved.
// Fetch the first row from the rowset
$r3 = $q3->fetch(PDO::FETCH_ASSOC);
$level3downlines = $r3['member'];
// Do actions specific to 1st row before the loop
echo "make orange juice";
// Then fetch the remaining rows with a loop
// and perform the their actions in the loop.
// The rowset record pointer has advanced beyond the 1st row
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
echo "make all juice";
}
In practice, I don't often do operations while fetching rows unless the rowset is very large. Instead I would more likely retrieve all rows as an array where I can more easily perform array operations on the set.
// Get all rows
$all_rows = $q3->fetchAll(PDO::FETCH_ASSOC);
// Pull the first row off the set
$first_row = array_shift($all_rows);
// do whatever with $first_row
// Loop over the other rows
foreach ($all_rows as $index => $row) {
// Do whatever with $row
}
Instead of using array_shift() in that way, when using $index => $row in the foreach loop, you could also check $index == 0 to operate on your first row. You may find this more understandable.
foreach ($q3->fetchAll(PDO::FETCH_ASSOC) as $index => $row) {
// First row
if ($index == 0) {
// Do first row actions
}
else {
// Do common actions for remaining rows.
}
}
I'm not sure if I understood you correctly, but you want to do a special action for the first row,
$sql3 = "SELECT member FROM levels where upline = ? AND level=1";
$q3 = $conn->prepare($sql3);
$q3->execute(array("$level2downlines"));
$first_row = true;
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
if ($first_row){
echo "make orange juice";
$first_row = false;
}else{
echo "make all juice";
}
}
UPDATE: Michael Berkowski's answer is better and faster.

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.

MYSQL PHP while loop, do something if there aren't a given amount of rows returned

I'm trying to figure out the best way to do something like this. Basically what I want to do (in a simple example) would be query the database and return the 3 rows, however if there aren't 3 rows, say there are 0, 1, or 2, then I want to put other data in place of the missing rows.
Say my query returns 2 rows. Then there should be 1 list element returned with other data.
Something like this:
http://i42.tinypic.com/30xhi1f.png
$query = mysql_query("SELECT * FROM posts LIMIT 3");
while($row = mysql_fetch_array($query))
{
print "<li>".$row['post']."</li>";
}
//(this is just to give an idea of what i would likkeee to be able to do
else
{
print "<li>Add something here</li>";
}
You can get the number of items in the resultset with mysql_num_rows. Just build the difference to find out how many items are "missing".
There are three ways I can think of, get the row count with mysql_num_rows, prime an array with three values and replace them as you loop the result set, or count down from three as your work, and finish the count with a second loop, like this:
$result = db_query($query);
$addRows = 3;
while ($row = mysql_fetch_assoc($result){
$addRows--;
// do your stuff
}
while ($addRows-- > 0) {
// do your replacement stuff
}
If you dont find a row, Add extra information accordingly.
$query = mysql_query("SELECT * FROM posts");
for($i=0;$i<3;$i++){
$row = mysql_fetch_array($query);
if($row){
print "<li>".$row['post']."</li>";
}
//(this is just to give an idea of what i would likkeee to be able to do
else{
print "<li>Add something here</li>";
}
}
Assuming you store the rows in an array or somesuch, you can simply do some padding with a while loop (depending how you generate the other data):
while (count($resultList) < 3) {
// add another row
}

MYSQL - Select specific value from a fetched array

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;

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