Understanding fetch_assoc() - php

I am trying to understand how/why fetch_assoc works the way it does.
I have the following piece of code:
$results = $connectToDb->fetch("SELECT * FROM customer");
$resultsArray = $results->fetch_assoc();
print_r($resultsArray); //print_r 1
while($row = $results->fetch_assoc()){
print_r($row); //print_r 2
}
The query returns 3 rows from a table.
Why does the 1st print_r return only the 1st row of the queried data but the 2nd print_r returns all 3? How does putting fetch_assoc into a while loop tell it to do the action more than once? I read that fetch_assoc returns either an associative array or NULL but I'm struggling to understand how the while loop "tells" fetch_assoc to fetch the next row, if that makes sense?
Thank you.

Lets try to understand your code and how it works:
$results = $connectToDb->fetch("SELECT * FROM customer");
A variable $results has a collection of rows which are returned by a query. The size of the collection can be from 0 to n.
$resultsArray = $results->fetch_assoc();
This line fetch the first element from the collection. If the collection is empty it will return NULL.
while($row = $results->fetch_assoc()){
}
It can be decoupled in the following steps:
Calculate $row = $results->fetch_assoc() and return array with elements or NULL.
Substitute $row = $results->fetch_assoc() in while with gotten value and get the following statements: while(array(with elements)) or while(NULL).
If it's while(array(with elements)) it resolves the while condition in True and allow to perform an iteration.
If it's while(NULL) it resolves the while condition in False and exits the loop.

I think it useful:
function get_posts(){
$posts = array();
if ($result = $mysqli->query("SELECT id, post_userid, name, lang, country, post_image, post_date, post_date_updated FROM posts ORDER BY `post_date` DESC ;")) {
while ($row = $result->fetch_assoc())
{
$posts[$row['id']] = $row ;
}
} else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
return $posts;
}

in your case, if you want to print 3 rows each by each, you need to call this $result->fetch_assoc() as a three times.
for example, when you call the first time first row will be fetched and removed from array list. then 2 rows remain now.
in Second call second row will fetched and removed from array list.then 1 row remain now.
so you can call 3 times because you have a 3 rows. it will give null value if you call fourth times.because array list is empty now.
now come to the while($row = $results->fetch_assoc() this also do the same job which we discussed above.

Related

Read data from mysqli_fetch_array like a multidimensional array?

When I use mysqli_fetch_array() I get an array, but how do I read the values? Is a While-Loop the only option, or can I pick any value from a row and column like a multidimensional array with index like row[0] column [3] ?
while loop fetches you a row per iteration.
You can get all rows as multidimensional array with mysqli_fetch_all
After that you can use pick your values with [rowNum][colNum]
But beware when your result has lot of rows - array can be very big and cause memory or other issues.
Update to clarify:
if you want to receive multidimensional array of rows there are two ways:
First: iterate over mysqli_result with fetch_assoc/fetch_array and append row to array:
$rows = array();
while ($row = mysqli_fetch_array($res)) {
$rows[] = $row;
}
echo $rows[0]['whatever'];
Second: receive all results with one function call:
$rows = mysqli_fetch_all($res, MYSQLI_ASSOC);
echo $rows[0]['whatever'];
That's all. No more methods are available.
It depends how you are returning your results from the database.
there are flags in your mysqli_fetch_array function which you can set to modify your returned result.
If you use $row = mysqli_fetch_array($result, MYSQLI_ASSOC); or in OOP $row = $result->fetch_array(MYSQLI_ASSOC);
then you can access your returned result as column name in your while loop like $row['name'] or $row['age']
Or if you use $row = mysqli_fetch_array($result, MYSQLI_NUM); or in OOP $row = $result->fetch_array(MYSQLI_NUM);
then you can access your returned result in while loop like $row[0] or $row[3]
Simple example would be
while($row = mysqli_fetch_array($result)) {
echo $row['name'] . " " . $row['age'];
}
For further information. Read PHP.net Fetch Array
Your question suggests that your goal is just to get a single value. If that is the case, you should limit your query to only return what you're looking for rather than getting everything and then finding what you want in the results with PHP.
For the column, specify the one column you want instead of using *, (SELECT one_column FROM your_table) and for the row, either use a WHERE clause to select a specific id (provided that is defined on your table) or use a LIMIT clause to select a specific row number from the result set. Then you won't have to fetch in a loop or fetch all. Your query result (if it's successful) will just have one row with one column, and you can fetch once and get your value.
Granted, if you're going to need to do this repeatedly (i.e. in a loop), it isn't the best approach.

mysqli fetch_array() is only turning first row of retrieved data into an array

What seems to be happening is $result_tag is only holding the first row of the sql data retrieved.
When I run the result query on SQl in returns a table with multiple rows.
However, when I var_dump() it, it only returns the first row and nothing else.
while($row = $results->fetch_array(MYSQLI_BOTH)) {
echo ....stuff that dont matter
//Now I want some SQL results based on a result from ^^^ $row['ID']
$result = $conn->query("SELECT tags.Tag FROM tags WHERE tags.results_ID =".$row['ID'] );
$result_tag = $result->fetch_array(MYSQLI_NUM);
//I got the results. Now I want to compare them to another array '$explode'
//and echo out elements that are the same
foreach($explode as $explodeValue){
foreach($result_tag as $tag){
if($tag == $explodeValue){
echo $explodeValue;
}
}
}
}//end of 1st while
You want to use fetch_all(); fetch_array() returns just one row (as an array)
See http://php.net/manual/en/mysqli-result.fetch-all.php
This is in fact what the outermost while is doing, fetching one row at a time with fetch_array()
Change to
$result = $conn->query("SELECT * FROM tags WHERE results_ID =".$row['ID'] );

PHP, mySQLi: store the value of an array element into a variable

I have an SQL query which returns a single row as a result. This row contains only one column, an integer. I want to put this integer into a variable.
I execute my query and return the results of the query in an array as such:
$row = mysqli_fetch_all($result, MYSQLI_ASSOC);
I would like to save the value of the single column of this single row into a variable, for example $age. How can this be done?
(This query will always return one row with one column, always an integer)
mysqli_fetch_all doesn't return a row. But set of rows.
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$value = reset($rows[0]);
but it would be more logical to use a more suitable function:
$row = mysqli_fetch_row($result);
$value = $row[0]; // here you go.
Since you have only one column and your query returns only one row, that means you'll get only one value, and since you're fetching an associative array, you can do the following and store it in a variable.
$row = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($row as $r) {
$test = $r['age'];
}
However, since you're getting only one value out of that, you can just leave the result type out, and get $test = $r[0].

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.

Disappear the arrays generated with mysql_fetch_array() after use?

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

Categories