fetch_array() - cannot add multiple array fields to new array - php

I am trying to return a json from a MySQL query to use it with xCode but I cannot get an array of several objects with multiple fields. I have read the documentation on php.net and over here, but I still can't get it.
1) Let's say I have a MySQL table with 3 rows (for example 3 people). Each row contains 3 fields (lastname, firstname, dateOfBirth):
$result = mysqli_query($mysqli, $sql) // where $sql = "SELECT * FROM tbl_syncList"
$resultArray = array();
while ($row = $result->fetch_array()) {
$resultArray[] = $row["lastname"];
}
echo json_encode($resultArray); // --> return "["Lastname1", "Lastname2"...] - that's okay, I understand I return the value of the key "lastname"
I don't know how to get an array with the entire rows (all the fields at once), like:
[["Firstname1", "Lastname1", "dateOfBirth1"], ["Firstname2", "Lastname2", "dateOfBirth2"],...]
I tried to replace
$resultArray[] = $row["lastname"];
with:
$resultArray[] = $row;
but it just gives the world...
"array"
...with no content. Does anyone have an idea?
Thanks a lot!

Are you sure the array is properly populated to begin with? print_r($resultArray) and see what you have there with = $row (which is correct).

Related

Query only get 1 row

I have a problem with a mysql_query - YES, i know it's updated and i need to upgrade it to pdo or mysqli..
However, it only get one row from the database, where it needed to pull out 3 rows. It only take the first row it find.
$result = mysql_query("SELECT * FROM packages WHERE workerid = '$id' AND approved = '1'");
$packed = array();
while($row = mysql_fetch_assoc($result)){
$packed[] = $row;
return $packed;
}
Right now i just print_r($packed);, which only give me the first row of the table. Workerid and approved are checked on the other rows, and they should be able to get pulled out. I have a similar code in my functions, which work perfect, so i cant really see the error here.
could try
while($row = mysql_fetch_assoc($result)){
array_push($packed, $row);
}
print_r($packed);
return $packed;
or
while($row = mysql_fetch_assoc($result)){
$packed[] = $row;
}
print_r($packed);
return $packed;
This should push each row return onto the end of the array. I am using print_r so that you can see if the array contains all the values you are looking for.

PHP MySQL Database - All rows into Multi-Dimensional Array

It's been a long while since I touched PHP so, I just need a refresher of sorts.
I have an HTML form that captures several lines of data (dataA, dataB, dataC & dataD) and inserts them into a database table (dataAll). I will be entering rows upon rows of data into "dataAll". What I'm looking to do is create a display.php page, where the code will take all of the data and place each cell into an array, or the row of an array, for example:
new Array = [["dataA", "dataA", "dataA", "dataA", "dataA"],
["dataB", "dataB", "dataB", "dataB", "dataB"],
["dataC", "dataC", "dataC", "dataC", "dataC"],
["dataD", "dataD", "dataD", "dataD", "dataD"]];
But I cannot remember the syntax on how to perform this task. Any help would be greatly appreciated.
The database is named 'compdata', the table is 'dataAll', and each row is 'dataA', 'dataB', 'dataC', 'dataD'.
Please let me know if I need to supply more information.
Since you asked for All rows, so the simple code for query is written below:
<?php
//after connection to mysql db using mysql_connect()
$sql = "Select dataA, dataB, dataC, dataD from `compdata`.`dataAll`" ;
$result = mysql_query($sql) ;
if(mysql_num_rows($result) > 0 ){
while($row = mysql_fetch_array($result)){
$dataArray[] = $row ;
}
}
echo '<pre>';
print_r($dataArray) ;//you got the desired 2D array with all results
?>
Assuming you are used to the old mysql_xxx functions:
$data = array ();
$result = mysql_query ('select * from dataAll');
while ($row = mysql_fetch_array ($restult, MYSQL_ASSOC))
$data [] = $row;
Result:
$data = array (
0=>array ('col_1'=>'dataA', 'col_2'=>dataB...),
1=>array ('col_1'=>'dataA', 'col_2'=>dataB...)
);
If you only want the numbers and not the column names, use MYSQL_NUM.
However, mysql functions are being replaced with the more generic PDO object so you might want to look into that.
$stmt = $pdo->query ('select * from dataAll');
$result = $pdo->fetchAll (PDO::FETCH_ASSOC); // Or PDO::FECTCH_NUM
Same results as above.

PHP Create new array per row of MYSQL Info, and store the arrays in a array

Don't ask me why I need it, I've tried to find it on the web and have failed.
I need it to find rows of info on my database and per row it creates a array with one row and stores that array in an array and carries on with the rest of the rows.
I will then generate a new word doc per array found in the array of arrays( I can do this myself.)
I'm sorry I don't make much sense, I don't really know how to explain this...
Do you mean:
$sql = "SELECT * FROM tbl";
$query = mysql_query($query, $connection);
$rows = array();
while ($row = mysql_fetch_array($query)) {
$rows[] = $row;
}
// You now have an array of your DB rows in $rows
foreach ($rows as $row) {
createWordDoc($row);
}
If you don't actually need to cache the rows you could do this directly in your first loop of course:
$rows = array();
while ($row = mysql_fetch_array($query)) {
createWordDoc($row);
}

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

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.

Categories