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
Related
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'] );
What's the best way to output all results from a SELECT query?
if ($result = mysqli_query($con, "SELECT name,pic_url FROM accounts")) {
$data = mysqli_fetch_assoc($result);
var_dump($data);
mysqli_free_result($result);
}
At present dumping of $data only outputs one result, even though a quick check of mysqli_num_rows() shows two results (and there are two rows in the table).
What's the best way to output this data?
I'm essentially looking to output the name field and the pic_url for each row so I was hoping to receive my results as an array which I can then loop through using foreach
you need to use a loop.
while ($data = mysqli_fetch_assoc($result)) {
var_dump($data);
}
Use simple while loop and store in an array:
if ($result = mysqli_query($con, "SELECT name,pic_url FROM accounts"))
{
while ($data[] = mysqli_fetch_assoc($result));
}
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 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 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.