I don't know why it's behaving like that in Php. In my first while() loop its showing data but second and third while() loop it's not return/showing any data. I'm using only one sql query to get same data 3 times.
Do you know why it's not showing data in second and third while loop in php ?
$query = mysql_query("SELECT * FROM contact_details ORDER BY family_name LIMIT 10");
while($a=mysql_fetch_array($query)){
echo $fname = $a['family_name'];
echo "<br/>";
}
while($b=mysql_fetch_array($query)){
echo $fname = $b['family_name'];
echo "<br/>";
}
while($c=mysql_fetch_array($query)){
echo $fname = $c['family_name'];
echo "<br/>";
}
If you need to use the same result multiple times, store it in a local array first. Once your first loop is completed, there is obviously 'no more data left' as otherwise the while wouldn't have stopped.
For example:
$query = mysql_query("SELECT * FROM contact_details ORDER BY family_name LIMIT 10");
$data = [];
while($row = mysql_fetch_array($query))
$data[] = $row;
foreach($data as $row)
// Do Stuff;
foreach($data as $row)
// Do Stuff;
foreach($data as $row)
// Do Stuff;
Mandatory disclaimer: the mysql_ family of functions is deprecated and will start breaking in future PHP versions. Consider switching to PDO or mysqli.
From PHP docs, mysql_fetch_array returns "Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows" , so second and third loop reuturns FLASE (no more data )
Because the array pointer has reached the end it is not possible to read it again.
you can use
mysql_data_seek ( resource $result , int $row_number );
mysql_data_seek ( $query , 0 );
i suggest that after every while loop try to reset the pointer to this query using this
mysql_data_seek($query, 0); // add this after every while loop.
//you need this to reset the pointer of the query.
try this out and check back if you still have problems.
this link has your same problem and is already answered PHP - Multiple while($row = mysql_fetch_array($variable)) { } ERRORS
Related
I have:
$query = mysql_query("SELECT ... ");
while($row = mysql_fetch_array($query)) { first time used; }
...
while($row = mysql_fetch_array($query)) { second time used; }
In second time it doesn't work. Why?
That's because the internal data pointer has reached its end. To reread the query, either rewind the pointer with mysql_data_seek(), or reissue the query.
A MySQL result resource has an internal pointer, much like a PHP array, and when you have run through it once, the pointer is at the end. You can reset the data pointer using mysql_data_seek():
while ($row = mysql_fetch_array($query)) {
// First time used
}
mysql_data_seek($query, 0);
while ($row = mysql_fetch_array($query)) {
// Second time used
}
...but what is arguably a better/more "standard" approach is to run through the pointer once, store the results in a temporary array and then you can release the memory used by the results and loop the data as an array:
// Do the query
$query = mysql_query("SELECT ... ");
// Cache the results in an array
$results = array();
while ($row = mysql_fetch_array($query)) {
$results[] = $row;
}
// Free the result resource
mysql_free_result($query);
foreach ($results as $row) {
// First time used
}
foreach ($results as $row) {
// Second time used
}
As a side note, it is more resource efficient to use mysql_fetch_assoc() or mysql_fetch_row() - almost every use case only calls for mysql_fetch_assoc(), it is very uncommon that you indexed keys for a MySQL result, and even less common that you need both indexed and associative.
It won't work the second time because you have already retrieved all of the rows. Therefore it returns false.
Reset the result pointer to the beginning of the result set before looping the second time using mysql_data_seek()
mysql_data_seek($query,0)
You've retrieved all the rows so you'll have to run another query or you can shove the values from your first loop into an array and then output that array for the second time you want to display the same data.
Or use mysql_data_seek()
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;
i have a query that should return 40 results:
$test = mysql_query(" SELECT fname FROM online_all WHERE verify_status = 'v' LIMIT 40 ");
if (!$test ) {print " - Mysql Error - ";echo fns_et_mysql_error(mysql_error());}
if i echo mysql_num_rows($test); i get 40. which means that i get the results
but when i print_r $roww = mysql_fetch_array($test); i get only one result.
there are no php errors.
You have to loop through the results with:
while($row = mysql_fetch_array($test)) {
// awesomeness with $row
}
Try using a loop.
while($row = mysql_fetch_array($test)){
}
mysql_fetch_array returns one row at a time. If you want to loop through all of them you do the following:
while ($row = mysql_fetch_array($test))
//Do something
http://php.net/manual/en/function.mysql-fetch-array.php
Check the documentation. mysql_fetch_array only fetches one row of data at a time. To get the data for all 40 rows you need a loop (like a for loop conditioned by mysql_num_rows).
You need to iterate the results from the query.
while($row = mysql_fetch_array($test))
{
// This is how you print fname.
echo $row[0];
}
Please refer to the documentation where there's also many useful tips of how you can use this function.
http://php.net/manual/en/function.mysql-fetch-array.php
You should also know that there exist another useful function for fetching results from mysql queries that fetches results as an associative array.
http://php.net/manual/en/function.mysql-fetch-assoc.php
You have to loop thru the rows:
while($row = mysql_fetch_array($test)){
var_dump($row);
//etectera
}
I currently have a database like the picture below.
Where there is a query that selects the rows with number1 equaling 1. When using
mysql_fetch_assoc()
in php I am only given the first is there any way to get the second? Like through a dimesional array like
array['number2'][2]
or something similar
Use repeated calls to mysql_fetch_assoc. It's documented right in the PHP manual.
http://php.net/manual/function.mysql-fetch-assoc.php
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
If you need to, you can use this to build up a multidimensional array for consumption in other parts of your script.
$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$i=-1;
while($row = mysqli_fetch_array($Subject))
{
$i++;
$SubjectCode[$i]['SubCode']=$row['SubCode'];
$SubjectCode[$i]['SubLongName']=$row['SubLongName'];
}
Here the while loop will fetch each row.All the columns of the row will be stored in $row variable(array),but when the next iteration happens it will be lost.So we copy the contents of array $row into a multidimensional array called $SubjectCode.contents of each row will be stored in first index of that array.This can be later reused in our script.
(I 'am new to PHP,so if anybody came across this who knows a better way please mention it along with a comment with my name so that I can learn new.)
This is another easy way
$sql_shakil ="SELECT app_id, doctor_id FROM patients WHERE doctor_id = 201 ORDER BY ABS(app_id) ASC";
if ($result = $con->query($sql_shakil)) {
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["app_id"], $row["doctor_id"]);
}
Demo Link
It looks like the complete solution has not been suggested yet
$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$Rows = array ();
while($row = mysqli_fetch_array($Subject))
{
$Rows [] = $row;
}
The $Rows [] = $row appends the row to the array. The result is a multidimensional array of all rows.
I have a typical database query:
$query = mysql_query('SELECT titulo,referencia FROM cursos WHERE tipo=1 AND estado=1');
and I can convert it in an array and print the data:
while ($results=mysql_fetch_array($query)): ?>
echo $results['referencia'];
// and so...
endwhile;
but in some cases I need to print the same data in another part of the web page, but the $results array seems to be empty (I use var_dump($results) and I get bool(false)). I plan to use what I learned reading Create PHP array from MySQL column, but not supposed to mysql_fetch_array() creates an array? So, what happen?
Tae, the reason that your $result is false at the end of the while loop is that mysql_fetch_array returns false when it reaches the end of the query set. (See the PHP Docs on the subject) When you reach the end of the query set $results is set to false and the while loop is exited. If you want to save the arrays (database row results) for later, then do as Chacha102 suggests and store each row as it is pulled from the database.
$data = array();
while($results = mysql_fetch_array($query)) {
$data[] = $results;
}
foreach ($data as $result_row) {
echo $result_row['referencia'];
... etc.
}
Try this
while($results = mysql_fetch_array($query))
{
$data[] = $results;
}
Now, all of your results are in $data, and you can do whatever you want from there.
As Anthony said, you might want to make sure that data is actually being retrieved from the query. Check if any results are being returned by echo mysql_num_rows($query). That should give you the number of rows you got