I would like to retrieve objects from the database in JSON using PHP and MySql. I would just like to know how to do this without having to create an array? Can it be done?
If so, can I get an example of how that can be done with this draft piece of code?
$sql = "SELECT Email , FirstName, LastName,Contact FROM tblUser where UserID=sessionID";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array ($result)) {
$arr = array(
$row["Email"],
$row["FirstName"],
$row["LastName"],
$row["Contact"]
);
array_push($json, $arr);
}
$jsonstring = json_encode($json);
echo $jsonstring;
$sql = "select name,email from contact";
$res = mysqli_query($conn,$sql) or die(mysqli_error($conn));
$num = mysqli_num_rows($res);
$json = array();
if($num > 0)
{
while ($obj=mysqli_fetch_object($res))
{
$json[] = $obj;
}
}
echo json_encode($json);
output:
[{"name":"test","email":"test#gmail.cmom"},{"name":"test1","email":"test1#gmail.cmom"}]
Related
This question already has answers here:
mysqli_fetch_array returning only one result
(3 answers)
Closed 3 years ago.
In $result should be all of users from datebase, but it takes only first person and shows error.
My php code:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once 'connect.php';
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = array();
$result['osoby'] = array();
$row = mysqli_fetch_assoc($response);
$index['name'] = $row['imie'];
$index['surname'] = $row['nazwisko'];
array_push($result['osoby'], $index);
$result['success'] = "1";
echo json_encode($result);
}
Its giving you 1 record because you are only printing 1 record,
Using $row = mysqli_fetch_assoc($response); will always give you last row if you not use loop here.
You need to use while loop to get all rows like:
<?php
$i = 0;
$result = array(); // initialize
while($row = mysqli_fetch_assoc($response)){
$result[$i]['name'] = $row['imie'];
$result[$i]['surname'] = $row['nazwisko']; // store in an array
$i++;
}
$finalResult['osoby'] = $result; // storing as you need
$finalResult['success'] = "1"; // no idea about this but adding this also
echo json_encode($finalResult); // encode with json
?>
You can loop the result-set and append an array of your values to the $result array.
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = ['osoby' => []];
while ($row = mysqli_fetch_assoc($response)) {
$result['osoby'][] = ['name' => $row['imie'], 'surname' => $row['nazwisko']];
}
$result['success'] = "1";
echo json_encode($result);
If you have the mysqlnd driver installed, you can also use mysqli_result::fetch_all() method
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = ['osoby' => mysqli_fetch_all($response, MYSQLI_ASSOC)];
$result['success'] = "1";
echo json_encode($result);
You have to loop the result array.
$resultJson = array();
$resultJson['osoby']=array()
$query = "SELECT imie,nazwisko FROM users";
$result = $mysql->query( $query );
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
// fetch information out of the $row..
$resultJson['osoby'][] = ['name' => $row['imie'], 'surname' => $row['nazwisko']];
}
}
print json_encode($resultJson);
Here is my code to encode data in JSON format, but it doesn't work. The result is []. Where is my mistake?
<?php
$conn = new mysqli('localhost','root','','project');
$data =array();
if(!empty($_GET['masp'])){
$masp =$_GET['masp'];
$sql ="SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)){
$r['masp'] =$data['masp'];
$r['loai'] =$data['loai'];
$r['hangsx']=$data['hangsx'];
$r['tensp']=$data['tensp'];
$r['img']=$data['img'];
$r['gia']=$data['gia'];
$r['nx']=$data['nx'];
}
}
}
print json_encode($data);
?>
You are setting your variables wrong.
In every while cycle you get a new $r variable that you want to add to your $data variable.
$conn = new mysqli('localhost', 'root', '', 'project');
$data = array();
if (!empty($_GET['masp'])) {
$masp = $_GET['masp'];
$sql = "SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn, $sql);
$i = 0;
if ($result) {
while ($r = mysqli_fetch_assoc($result)) {
$data[$i]['masp'] = $r['masp'];
$data[$i]['loai'] = $r['loai'];
$data[$i]['hangsx'] = $r['hangsx']];
$data[$i]['tensp'] = $r['tensp'];
$data[$i]['img'] = $r['img'];
$data[$i]['gia'] = $r['gia'];
$data[$i]['nx'] = $r['nx'];
$i += 1;
}
}
}
print json_encode($data);
You make mistake. You should swap variable data with r inner loop, but probably than also will works unpropely. write in while loop $data [] = $r;
i had this php code :
<?php
include "../mainmenu/koneksi.php";
// Start with the list of animals
$sql = "SELECT * FROM data_binatang";
$rows = array();
$res = mysql_query($sql);
for($i=0; $i<mysql_num_rows($res); ++$i){
$row1 = mysql_fetch_assoc($res);
$id_binatang = $row1['id_binatang'];
$sql = "SELECT * FROM data_waktu_vaksinasi WHERE id_binatang = $id_binatang AND (status_vaksin = 'belum' OR status_vaksin IS NULL) ORDER BY tanggal_vaksin ASC LIMIT 1";
$res2 = mysql_query($sql);
$row2 = mysql_fetch_assoc($res2);
$arr[$id_binatang] = array();
array_push($arr[$id_binatang], $row1['nama_binatang'], $row1['id_user'], $row1['jenis_binatang'], $row1['ras_binatang'], $row1['foto_binatang'], $row2['nama_vaksin'], $row2['id_data_waktu_vaksinasi'], $row2['status_vaksin'], $row2['tanggal_vaksin'], $row2['tanggal_datang']);
}
echo "RESULT:";
echo "<table border=1><tr><th>id binatang</th><th>nama binatang</th><th>id user</th><th>jenis binatang</th><th>ras binatang</th><th>foto binatang</th><th>nama vaksin</th><th>id data waktu vaksin</th><th>status vaksin</th><th>tanggal vaksin</th><th>tanggal datang</th></tr>";
foreach($arr as $key => $val){
echo "<tr><td>$key</td><td>".implode("</td><td>", $val)."</td></tr><br>";
}
?>
and here's the result
now i want to generate the table into json, but i don't know what to put inside the json encode, i tried:
echo '{"data_vaksinasi_menu":'.json_encode($arr[$id_binatang]).'}';
but instead it gave me null
Try this:
echo json_encode(array('data_vaksinasi_menu' => $arr));
I need to encode a table content to JSON in order to insert it into a file.
The output has to be as following :
{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}
Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.
The only thing I could manage for the moment is this :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
$index++;
}
echo json_encode($return_arr);
And here is the output I get :
[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]
Thanks a lot !!!
UPDATED
Working code :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}
echo json_encode($return_arr);
}
You were close. I noticed you want final output to be an object not an array, because the outer brackets are {} not []. So you need a different object type, and you need to use each row's name as the key for storing that row.
$return_obj = new stdClass();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
$return_obj->$name = [$row]; // for PHP < 5.4 use array($row)
}
echo json_encode($return_obj);
This loop is enough, to create the desired JSON:
$return_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
}
echo json_encode($return_arr);
I was working on it a lot of time and Create mash/mysql-json-serializer package.
https://github.com/AndreyMashukov/mysql-json-serializer
You can select Json_array of json_objects and etc. It support ManyToMany, oneToMany, manyToOne relations
SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res
<?php
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>
My mind got stuck when i try to develope this:
i have a table in my database called "article" whit two column, "name" and "price".
How can i extract all rows from my table and echo all column in JSON?
i really can't understand how to convert result in JSON. My mind it's stuck like never before. i need to echo something like this:
{"items": {
"items":[
{"name": "firstitemname",
"price": "5"
},
{"name": "secondone",
"years": "3"
}],
}}
Please help me fixing my buggy code!
<?php
$query = mysql_query("SELECT * FROM itemlist");
$nameitem = array();
$itemprice = array();
while($row = mysql_fetch_array($query)){
array_push($nameitem , $row['nome']);
array_push($itemprice, $row['pix']);
}
?>
You would simply edit your PHP as follows.
<?php
$query = mysql_query("SELECT * FROM itemlist");
$items = array();
while($row = mysql_fetch_array($query)){
$items[] = array('name' => $row['nome'], 'price' => $row['pix']);
}
echo json_encode(array('items'=>$items));
?>
http://php.net/manual/en/function.json-encode.php
JSON is super easy to deal with in PHP.
If you're using PHP 5.2 or greater, you can use the json_encode function to do exactly what you're trying to do: http://www.php.net/manual/en/function.json-encode.php
For your code, you should be able to do something like this:
$query = mysql_query("SELECT * FROM itemlist");
$json_output = array();
while($row = mysql_fetch_assoc($query)){
$json_output[] = json_encode($row);
}
Here, $json_output will contain an array of strings with the json encoded string of each row as each array element. You can output these as you please.
<?php
$result = mysql_query("select * from item_list");
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
print json_encode($rows);
?>
Convert Data table to json with following code :
echo(json_encode($array));
for example ( select data from mysql and convert to json ):
public function SELECT($tableName,$conditions){
$connection = mysqli_connect($hostname, $userName, $password,$dbName);
try {
if (!$connection)
die("Connection failed: " . $connection->connect_error);
else
{
$qry = "";
if(!$this->IsNullOrEmptyString($conditions))
$qry = "SELECT * FROM `".$tableName."` WHERE ".$conditions;
else
$qry = "SELECT * FROM `".$tableName."`";
$result = mysqli_query( $connection, $qry);
if($result) {
$emparray = array();
while($row =mysqli_fetch_assoc($result))
$emparray[] = $row;
echo(json_encode($emparray));
}
else
echo(mysqli_error($connection));
}
mysqli_close($connection);
} catch(Exception $ex) {
mysqli_close($connection);
echo($ex->getMessage());
}
}