Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use query twice mysql_fetch_array

Tags:

php

a simple

$stuff = mysql_query("SELECT * FROM users");

while($s = mysql_fetch_array($stuff)){
# ....
}

while($r = mysql_fetch_array($stuff)){
# ...
}

The last while() does not work. I have tried run foreach($stuff as $s) but then i get invalid array error.

How can i use the same query twice?

like image 614
Karem Avatar asked Nov 27 '11 12:11

Karem


People also ask

What is mysql_fetch_array () function?

mysql_fetch_array is a PHP function that will allow you to access data stored in the result returned from the TRUE mysql_query if u want to know what is returned when you used the mysql_query function to query a Mysql database. It is not something that you can directly manipulate. Syntax.

What is the purpose of using mysql_fetch_array () & Mysqli_num_rows ()?

The mysqli_fetch_array() function is used to fetch rows from the database and store them as an array. The array can be fetched as an associative array, as a numeric array or both. Associative arrays are the arrays where the indexes are the names of the individual columns of the table.

What is difference between mysql_fetch_array () Mysql_fetch_row () and Mysql_fetch_object ()?

1. mysql_fetch_row($result): where $result is the result resource returned from a successful query executed using the mysql_query() function. 2. mysql_fetch_array($result): Return the current row with both associative and numeric indexes where each column can either be accessed by 0, 1, 2, etc., or the column name.

How can fetch data without while loop in PHP?

You can just call mysql_fetch_assoc() (or any similar function) one. Like this: $sql = "SELECT * FROM table"; $row = mysql_fetch_assoc( mysql_query($sql) ); echo $row['title']; This is the easiest and most readable way to do this with the MySQL functions.


2 Answers

$stuff = mysql_query("SELECT * FROM users");

while($s = mysql_fetch_array($stuff)){
# ....
}
// add this line
mysql_data_seek( $stuff, 0 );

while($r = mysql_fetch_array($stuff)){
# ...
}

Should do the trick

Another way is of course to store your result in an array and reuse that

like image 186
abcde123483 Avatar answered Sep 17 '22 13:09

abcde123483


$stuff = mysql_query("SELECT * FROM users");

while($s = mysql_fetch_array($stuff)){
# ....
}
mysql_data_seek($stuff, 0);
while($r = mysql_fetch_array($stuff)){
# ...
}
//ref: http://www.php.net/manual/en/function.mysql-data-seek.php
like image 32
Sudhir Bastakoti Avatar answered Sep 20 '22 13:09

Sudhir Bastakoti