mysql_fetch_row not returning full array - php

I am attempting to loop through rows in MySQL with the following code. Unfortunately, the mysql_fetch_row function is only returning the first row of my query (I confirmed this with print_r). When I use mysql_num_rowsit returns the correct number of rows for that query(2). Any idea why mysql_fetch_row is returning only the first row?
$query = 'SELECT firstName FROM profiles WHERE city="Phoenix" and lastName ="Smith"';
$result = mysql_query($query);
$row = mysql_fetch_row($result);
print_r($row); //This returns only 1 array item: Array ( [0] => John)
$a=mysql_num_rows($result);
print_r($a); //This returns 2
I have also run the same query in MySQL and it returns both rows ("John" and "Jim").
Thanks for the help.

Just perform mysql_fetch_row twice (or in a loop). By definition (if you read the documentation) it returns only one row at once. So:
while ($row = mysql_fetch_row($result)) {
var_dump($row);
}

You want to put it in a while loop:
while ($row = mysql_fetch_array($result)) {
$firstName = $row['firstName'];
echo("$firstName<br />");
}
What this does is for each result (row) it finds, it fetches the data you want and displays it. So it gets the first result, displays the name, loops back to the top, fetches the second result, displays that name and so on, then once you have no more results that match the query criteria, the while loop is ended.

PHP accesses the SQL Results in order of how they're buffered. You'll need to run a loop to access all the contents.
If you wish to load everything into an array:
$allRows=array();
while($row=mysql_fetch_assoc($result) {
$allRows[]=$row;
}

You can use any of the following one:
while ($row = mysql_fetch_array($result))
{
echo $row['firstName'];
}
or
while ($row = mysql_fetch_assoc($result))
{
echo $row['firstName'];
}
or
while ($row = mysql_fetch_object($result))
{
echo $row->firstName;
}

Related

php foreach not iterating

$email is the name of a table in my database. When I execute the mysql query in phpmyadmin, I correctly get two casenums, 1 and 3.
However, when I try to loop through the array, echo $caseNum."<br>"; prints
1
1
instead of
1
3
The code:
$_SESSION['caseNums'] = mysql_fetch_array(mysql_query("SELECT `casenum` FROM `$email`"));
$_SESSION['cases'] = array();
foreach($_SESSION['caseNums'] as $caseNum) {
echo $caseNum."<BR>";
}
That's to be expected. mysql_fetch_array() returns a SINGLE row of data from your query, with dual string+integer keys.
In other words, you're printing out the value retrieved from the first row of data only, and printing it twice because it was duplicated in the returned array.
You need:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_row($result)) {
$_SESSION['caseNums'][] = $row[0];
}

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.

query not resolving right, how to?

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
}

How to select multiple rows from mysql with one query and use them in php

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.

mysql_fetch_array does not retrieve all rows

$query = "SELECT * FROM table";
$result = mysql_query($query, $db);
$all = mysql_fetch_assoc($result);
echo mysql_num_rows($result) . ":" . count($all);
This returns
2063:7
I have not used count before, so I'm not 100% sure it's not counting the table columns. It's late and I might be going nuts.
Here's another example of what's happening:
$result = mysql_query($query, $db);
echo "Rows: " . mysql_num_rows($result) . " <BR />";
$player_array = mysql_fetch_assoc($result);
echo "<pre>";
print_r($player_array);
echo "</pre>";
Which outputs:
Rows: 9
Array
(
[playerID] => 10000030
)
TL;DR: I submit queries which return multiple rows, but fetch_array only gives me a small portion of those rows in the resulting array.
mysql_fetch_assoc returns only one row in once you have to use loop to retrieve all rows
while($row = mysql_fetch_assoc($result))
{
print_r($row);
}
Every call to mysql_fetch_assoc($result); gives you one row of the result set:
(from the documentation)
mysql_fetch_assoc — Fetch a result row as an associative array
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.
You have to use the function in a loop:
$all = array();
while(($row = mysql_fetch_assoc($result))) {
$all[] = $row;
}
The example in the document shows how it is done.
mysql_fetch_assoc doesn't work that way, you need to call it multiple times to get all rows. Like this:
while ($row = mysql_fetch_assoc($db_result))
{
print_r($row);
}

Categories