PHP storing a two dimension array from MySQL query - php

I have a simple question. I have an array that has two columns (id, name) that is a result of a MySQL query. I want to store the result of the query into a array variable so i can access each element when i need to.
I am able to store a one dimension array like the following:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row['name'];
}
How can I store and access a two dimensional array? Also is it best to use a for loop or while loop to store these?

Simply do this:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
To access your results you can do this:
$firstResultRow = $array[0];
$firstResultName = $array[0]['id'];
$firstResultName = $array[0]['name'];
This will tell you if a particular row exists:
if(isset($array[$x])) {
$aRow = $row[$x];
// do stuff with $aRow;
}
This will give you a row count for your array:
$rowCount = count($array);
This will set up a loop through your array:
foreach($array as $index => $row) {
$id = $row['id']
$name = $row['name'];
// $index will have the array index of the current row. 0 -> $rowCount - 1
}

Don't specifically store the index of $row but rather store the whole row.
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
Then $array will have the following structure:
$array = [
[
'id'=> ...,
'name' => ...,
],
...
];
To initially access all of the results from [mysqli_fetch_assoc][1] you will want to use the while loop like you are, mysqli_fetch_assoc will continue to output results until it doesn't have any more data. Then at that point mysqli_fetch_assoc will return NULL. This will signal to your while loop to stop iterating.
Then to access variables inside of your $array, I recommend using foreach.
You could then do:
foreach ($array as $row) {
do something with $row['name'] or $row['id']
}
You could also use a for loop, but it takes more work IMO. Compare the above with this alternative:
for ($i = 0; $i < count($array); $i++) {
$row = $array[$i];
do something with $row['name'] or $row['id']
}

Related

When I try to access to array items I only get the 1. one

Here's my Query
$rows = $mydb->get_results("SELECT title, description
FROM site_info
WHERE site_id='$id';");
I get something like:
Title1 Desc1
Title2 Desc2
etc.
I want to put that data in array so I do:
$data = array();
foreach ($rows as $obj) {
$data['title'] = $obj->title;
$data['description'] = $obj->description;
}
When I do:
print_r($data);
I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.
You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.
So either do:-
$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
$data[$key]['title'] = $obj->title;
$data[$key]['description'] = $obj->description;
}
Or
$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
$data[$i]['title'] = $obj->title;
$data[$i]['description'] = $obj->description;
$i++;// increase the counter each time after assignment to create new index
}
For display again use foreach()
foreach ($data as $dat) {
echo $dat['title'];
echo $dat['description'];
}
If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");
If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);
When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.
echo "<ul>";
foreach ($rows as $obj) {
echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
}
}
echo "</ul>";
If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.
foreach ($rows as $obj) {
$data[] = ['title' => $obj->title, 'id' => $obj->id];
}
The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.

How to extract value from foreach loop by json_encode

I have php result set, and from these result i am extracting value using php foreach loop. I put the foreach loop value in array $summery[]. but when i try to print value its print value at once. but i need separate value/result set for each foreach loop as json code so that i can print each result separately. My foreach loop following :
foreach($result_UserWrSet as $UserWrInfo) {
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
}
print json_encode($summery);
My result become
["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done","01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]
but i need :
[["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done"],["01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]]
Use this code, you need to use another array in which all the sub array's to be pushed and encode that array after pushing all the items into it
<?php
$dataArray = array(); /// empty array in which sub array's to be pushed..
foreach($result_UserWrSet as $UserWrInfo) {
$summery= array();
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
////Push sub array i.e summary into the main array...
$dataArray[] = $summery;
}
print json_encode($dataArray);
?>
You need a multidimensional array, you can follow below code:
$result_UserWrSet = array(
'0' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'),
'1' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'));
foreach($result_UserWrSet as $key => $UserWrInfo) {
$summery[$key][]=$UserWrInfo['wr_id'];
$summery[$key][]=$UserWrInfo['wr_number'];
$summery[$key][]=$UserWrInfo['wr_title'];
}
print json_encode($summery);
output: [["12","785","title1"],["12","785","title1"]]
Good Luck :)
Currently, you are just adding new items to a one dimensional array. You need to create a separate array per result, like this:
foreach($result_UserWrSet as $UserWrInfo) {
$item = array();
// Change all $summary in the loop to: $item, like this:
$item[]=$UserWrInfo['wr_id'];
$item[]=$UserWrInfo['wr_number'];
$item[]=$UserWrInfo['wr_title'];
//...and so on
// Then add this last in your loop:
$summary[] = $item;
}
This will create one array per iteration that is put in the main array, which then becomes a multi dimensional array.

Advancing the "cursor" in an associative array PHP

I have an associative array like such:
$arr = array('format' => 'A4', 'coulor' => 'red', 'height' = > '30');
I would like to use it in an mysql query like such:
reset($arr);
$first_key = key($arr); // get the first key of the array
$sql = "// sql query here...";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result))
{
echo $row[$first_key]; // will echo out the content of a table field
}
How to advance the cursor of this associative array so I can echo out the content of the next column in the mysql table
If you really need to use the keys of your $arr then just do:
while($row = mysqli_fetch_assoc($result))
{
foreach($arr as $key=>$v)
echo $row[$key];
}
Otherwise you can simply use mysqli_fetch_row() In this way your keys are integers, and you can get the next by doing:
while($row = mysqli_fetch_row($result)) {
echo $row[0]; // will echo out the content of a table field
echo $row[1]; // will echo out the content of a table field
}

PHP - Multidimensional Array

I am basically trying to fetch results from a SQL database and load that into a multidimensional array so i can use them later on in the page.
while($row = mysqli_fetch_array($result))
{
$send = array
(
array($row['Name'],$row['Email'],$row['Mobile'])
);
$count = $count + 1;
}
That is what i am using to get the results which if i print within the while loop it will echo all the results. However when putting it into the array it loads each result into the array as the first result. My initial plan was to use a counting variable to set where in the array the result was set to with this adding by one each time. I am not certain how to specify where to add the result i thought something along the lines of
$send = array[$count]
(
array.....
so i could then refer to the results as 0 to count length but i am not sure how to make this work. Or ,which i presume, if there is a much easier and better way of going about it. I am also not sure if this is necessary as surely the results seem to be in an array when gathered from the SQL database but i am unsure if this array is populated with each while loop or stored and can be accessed at any point
If any one can give me an example of something similar or point me at some documentation much appreciated
Try this:
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$send[$count] = array($row['Name'], $row['Email'], $row['Mobile']);
$count++;
}
I have a better way for you. You could also use the id for your index, if you have one:
while ($row = mysqli_fetch_array($result)) {
$send[$row['id']] = array(
"Name" => $row['Name'],
"Email" => $row['Email'],
"Mobile" => $row['Mobile']
);
}
You can use:
$count = 0;
while($row = mysqli_fetch_array($result))
{
$send[$count] = $row;
$count ++;
}
Also you might want to use the table id as an array index, so you can access the records by ID later. In that case you can do:
while($row = mysqli_fetch_array($result))
{
$send[$row['id']] = $row;
}
You're declaring your array inside your loop. So it will reset it every time.
$send = array();
while($row = mysqli_fetch_array($result))
{
$send[] = array($row['Name'],$row['Email'],$row['Mobile']);
}

adding items to array during foreach on the array

I wish to run a foreach on a load of ID's.
However each of the items in the foreach is a select query and if it finds more ID's they need to be added to the array that is being run in the foreach.
E.g
$ids = array();
foreach($ids as $id)
{
SELECT id FROM table WHERE otherid = $id;
foreach ($query2->result_array() as $row)
{
array_push($array, $row['id']);
}
}
This is obviously pseudocode so no need to correct my SQL etc. I just need for the foreach to continue if it finds more ID's.
Possible?
I have tried adding an & here -> foreach($ids as &$id) as somebody else on here has suggested in a similar question. This doesn't seem to work.
foreach actually makes a copy of your array to loop though, you will need to use while.
while(list($id_key, $id) = each($ids)){
//your code
$ids[] = $row[id];
}
You should simply be able to just reference the original array ie
foreach ($query2->result_array() as $row)
{
$id[] = $row;
}
This will automatically assign an auto incremented key to the the new array element and add it to the $id array. I assume this is what you are after.
Try to iterate with a variable:
$ids = array();
$i = 0;
while ($i < count($ids)) {
$query2->query(SELECT id FROM table WHERE otherid = $ids[$i]);
foreach ($query2->result_array() as $row)
$ids []= $row['id'];
$i++;
}
For similar problems, I have always used two different arrays. Such code can run a query for every id only one time. I don't think it would be possible with only one array+foreach;
The following code is pretty simple. It keeps finding new ids until there are no new ids.
$ids = array();
$new = array();
$new = $ids;
do {
foreach($new as $n) {
$new = array();
//// HERE PUT YOUR CODE TO RUN A QUERY AND MAYBE PUSH A NEW ID TO $new \\\\
}
$ids = array_merge($ids,$new);
} while (count($new)!==0);

Categories