Read data from mysqli_fetch_array like a multidimensional array? - php

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.

Related

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.

Unexpected result in mysql_fetch_array

I am using a complex join statement to get data from my 'items' table where 'column1' is equal to the value of table2.ID
This is in a mysql_query() statement, and it should return 3 rows.
Now my understanding is that by using
$array=mysql_fetch_array($queryresult);
I can then loop through each 'row' using a
foreach($array as $output) {
echo $output['ID'];
}
This is however not returning what i want. Using print_r on $output is outputting non-sensical information.
So, yes it is ver much back to basics, but obviously i have missed the point.
You need to use while loop:
while($row = mysql_fetch_array($queryresult)){
// handle each row
}
This is how I do it. This is by far not the end all solution... Just an example of how I do it.
$result = mysql_query($query, $dbconnect) or trigger_error("SQL", E_USER_ERROR);
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["questionId"];
echo $row["questionText"];
echo $row["questionReview"];
$i++;
}
http://php.net/manual/en/function.mysql-fetch-array.php
$array has a single row in it when you get to the loop, so when you say $output['ID'] you are one level deeper than you are expecting, walking through the columns instead of each row. When the ids don't exist or are translating to integers, thats where the nonsense comes in.
Use while($row = mysql_fetch_array($queryresult)) to walk through each row in the result set, then access the column values from $row['id'], $row['name'], etc. It will return false when there are no more rows.
The result will always be a single flat array with a single row per index id, regardless of the join dimensions.

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