Easily add data from database to multidimensional array using php - php

How can I easily add data from MySQL to a multidimensional array in PHP? I am making a search box and I want to store the first name, and the last name in the array.
Why does not this work.
$result = mysqli_query($db, $sql) or die(mysqli_error());
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[$row['primary']] = $row['firstname'], $row['lastname'];
}

$data[$row['primary']] = array($row['firstname'], $row['lastname']);

Related

Get query results in array of arrays using json_encode in php

I am trying to fetch the list of id's associated with mobile number using following code.
$sql = "SELECT id FROM complaints WHERE mobile=1555521555";
$r = mysqli_query($conn,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"id"=>$res['id']
)
);
header('Content-Type:application/json');
echo json_encode(array("result"=>$result));
mysqli_close($conn);
But it only result me a single id every time as below instead of list of id's
{"result":[{"id":"82925318"}]}
Actual query result is -
How do I get the multiple results in array of arrays format or in multidimensional array? Like below -
{"result":[{"id":"82925318"}, {"id":"82925319"}]}
You need loop to get all data
$result = array();
while($res = mysqli_fetch_array($r))
{
array_push($result,array(
"id"=>$res['id']
)
);
}

how to retrieve value only of JSON by php from database?

may I know how to retrieve the value only array in json instead of the whole json object in php from the database?
<?php
require_once('dbConnect.php');
$sql = "SELECT RestaurantName FROM Restaurant";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$restaurantArray = array();
while($rows = mysqli_fetch_assoc($result)) {
$restaurantArray[] = $rows;
}
echo json_encode($restaurantArray);
mysqli_close($connection);
?>
For example,
["Afonso Cláudio", "Água Doce do Norte"]
instead of
[{"city":"Afonso Cláudio"},{"city":"Água Doce do Norte"}]
When fetching data from the database as assoc, you will get an associative array (which when converted to json will become a json object) as result.
What you are currently doing is adding the row (which is an associative array with one key-value) to your result array. If you only want the city, you can easily fetch only that data from the assoc-array.
Changing
$restaurantArray[] = $rows;
to
$resturantArray[] = $rows['city'];
should do the trick.
Additionally, if you wanted to reformat the data in the result, and not just push the city name to it, a array_map call could be used:
$result = array_map(function($assocArr) {
return $assocArr['city']; // Or whatever you want the value to be.
},
$resturantArray);
echo json_encode($result);
How about you change this line:
$restaurantArray[] = $rows;
With:
$restaurantArray[] = $rows['city']; // (or 'RestaurantName')

Json Encode Multi dimension array format

im retrieving some data in my database table and than convert to json, but i need to create a array with this structire in my php loop
["postcode"=>"townName"...]
but instead is giving me
["postcode=>townName"...]
My code:
$sql = "SELECT * FROM uk_postcodes";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = $row['postcode']."=>".$row['town'];
}
echo json_encode($dname_list);
In that line:
$dname_list[] = $row['postcode']."=>".$row['town'];
You're creating a string with "=>" in the middle (see string concatenation). You should specify the key of the array to be the postcode field, and the value - town field. Just change that line to:
$dname_list[$row['postcode']] = $row['town'];
http://php.net/manual/en/language.types.array.php

Array in PHP does not work

I am trying to add array data from mysql. But only the last row details are getting added. I tried array_push also but did not work. Can any one help
$sql="SELECT * FROM server_details";
$result=mysqli_query($dbC, $sql);
while ($row = mysqli_fetch_array($result))
{
$services=array(
$row['server_name'] => array($row['server_add'] => $row['port'])
);
}
By not creating a new array in every iteration of the loop :
$sql = "SELECT * FROM server_details";
$result = mysqli_query($dbC, $sql);
$services = array();
while ($row = mysqli_fetch_array($result)) {
$services[$row['server_name']] = array($row['server_add'] => $row['port']);
}
Perhaps you're looking for this:
$services[ $row['server_name'] ] = array($row['server_add'] => $row['port']);
In the end you'll get in your $services variable an associative array, indexed by server_name column values.
If they're not unique, you should do this instead...
$services[ $row['server_name'] ][] = array($row['server_add'] => $row['port']);
This way you'll still get the same associative array, but its values will be indexed arrays; thus you won't lose any information for records with the same server_name.

Storing database records into array

I would want to create an array that will hold records retrieved from a database using a query of SELECT statement.
The records to be retrieved have multiple fields such as lastname, firstname, mi and 20 more fields. What would be the best approach on coding this function?
alright i have followed what prisoner have given below.. the next question is how do i search through this kind of array using queries? for example i want to search for a username..
<?php
// run query
$query = mysql_query("SELECT * FROM table");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['username']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}

Categories