Output multiple results with mysqli_fetch_assoc - php

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));
}

Related

SHOW TABLES not returning correct items in array

I have multiple tables named like so MOM2016, MOM2017, MOM2018.
When i run query in phpmyadmin
SHOW TABLES LIKE 'MOM%'
it returns 3 items as expected.
BUT!!!! When i run in php, my code seem to give me only 1 item in the array (first one only MOM2016).
$sql = "SHOW TABLES LIKE 'MOM%'";
$result = $conn->query($sql);
$dbArray = $result->fetch_assoc();
echo "DEBUG:".count($dbArray);
This give:
DEBUG:1
My php code is wrong? Pls help.
If you want to get all the results at once,
$dbArray = $result->fetch_all();
echo "DEBUG:".count($dbArray);
Iterate through your fetch resource
$dbArray = array();
while ($row = $result->fetch_assoc()) {
$dbArray[] = $row;
}
print "DEBUG: " . count($dbArray);

Selecting multiple rows in a table

I need to select multiple comments (if there are any) based on the photo_id. As I understand it you can use the WHERE clause but I'm not exactly sure how to select multiple ones and store them in some kind of array?
e.g.
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
$row = $result->fetch_assoc(); // but there's more than 1 row
If for example $photo1id == 21, how do I get all the comments (2 in this case)? Some kind of while loop?
At the end of the PHP file I have this:
echo json_encode(array('photo1id'=>$photo1id));
I need to store each row in that array somehow because I need to retrieve the data in another PHP file using $.getJSON. Or perhaps there is a better solution to this.
Loop through it and generate an array -
while($row = $result->fetch_assoc()) {
$comments[] = $row;
}
After that you can send the array as json.
echo json_encode($comments);
Is there is more rows, you need to use a loop.
while ($row = $result->fetch_assoc()) {
// your code here
}
Try the code below:
//Run query
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
//While there is a result, fetch it
while($row = $result->fetch_assoc()) {
//Do what you need to do with the comment
}
If you don't want to print the code straight away you can just create an array:
$x=0;
while($row = $result->fetch_assoc()) {
$comment[$x]=$row['comment'];
$x++;
}

How can I get and display all values of a certain field in a sql table?

I have a table wherein I need to get all the data in one column/field, but I can't seem to make it work with the code I have below:
$con=mysqli_connect("localhost","root","","database");
$result = mysqli_query($con,"select * from client");
$row = mysqli_fetch_array($result111);
echo $row['name'];
With the code above, it only prints one statement, which happens to be the first value in the table. I have 11 more data in the table and they are not printed with this.
You need to loop through the recordsets .. (A while loop will do) Something like this will help
$con=mysqli_connect("localhost","root","","database");
$result = mysqli_query($con,"select * from client");
while($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
The mysqli_fetch_array() function will return the next element from the array, and it will return false when you have ran out of records. This is how you can use while loops to loop through the data, like so:
while ($record = mysqli_fetch_array($result)) {
// do something with the data...
echo $record['column_name'];
}

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

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