JSON encoding not working - php

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;

Related

Fetch data from database using json without using an array

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"}]

MySQL Query Returns 0 When Running Multirowed Response Query

When I run the following code In PHP
$connect = mysqli_connect("localhost", "root", "dbpass", "db");
function csvfromarray($array) {
$result = $array[0]+","+$array[1];
return $result;
}
$query = mysqli_query($connect, "SELECT * FROM dbtable");
$row = mysqli_fetch_assoc($query);
$data = array();
$i = 0;
while($row = mysqli_fetch_assoc($query)) {
$data[$i] = $row['last'];
$i++;
}
$csv = csvfromarray($data);
echo $csv;
mysqli_close();
I end up getting an echoed response of "0" when I should be returning "lname1,lname2".
All of chris85's stuff is correct...
Here's a tidy up:
$query=mysqli_query($connect,"SELECT `last` FROM dbtable");
$data=array();
while($row=mysqli_fetch_assoc($query)) {
$data[]=$row['last']; // push into array
}
echo implode(',',$data); // echo comma-separated values
mysqli_close();

Printing multiple table queries using json_encode in php

I need to print multiple database queries using json_encode(). I have this code below that outputs database records using json_encode. This works fine.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('SELECT username,firstname,lastname FROM user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
echo json_encode($data);
?>
I need to add another database query so that I can print them together using the same json_encode. Here is the database query that I want to add so that I can print them together using json_encode:
<?php
include('db.php');
$result = $db->prepare('SELECT price AS price1,goods AS product FROM provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
echo json_encode($data_pro);
?>
How can I accomplish this?
I think this might hit what you're looking for.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('select username,firstname,lastname from user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
$result = $db->prepare('select price as price1,goods as product from provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
// Combine both arrays in a new variable
$all_data['user'] = $data;
$all_data['pro'] = $data_pro;
echo json_encode($all_data);

Collect all ID's MySQL

I've done this:
$result = mysql_query("SELECT image, id FROM store WHERE username = '$username_show'");
$num_rows = mysql_num_rows($result);
$ids = mysql_fetch_assoc($result);
$ids = $ids['id'];
for ($i = 0; $i < $num_rows; $i++) {
echo "<img src='get.php?id=$ids[$i]' height='300'><p/>";
}
I want to show all of my photos that has that username. But the $ids array only gets one index, and that's the last ID. What am I doing wrong?
Like #Matthew said thet are deprecated use :
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT image, id FROM store WHERE username = '$username_show'");
$row = $result->fetch_assoc();
echo htmlentities($row['row']);
// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT image, id FROM store WHERE username = '$username_show'");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['row']);
To answer your comment :
- use the array function
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
$result = $mysqli->query("SELECT id FROM store WHERE username = '$username_show'");
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}

json formatting_adding a tag to it

here is the PHP file that im using to generate the JSON with:
<?
$databasehost = "wbw.com";
$databasename = "wtest";
$databaseusername ="w";
$databasepassword = "123";
$query = "SELECT * FROM `and` LIMIT 0 , 30";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query.'\n';
echo mysql_error();
}
else
{
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
?>
The problem with it is that it generates a result like this:
[{"Reg_user_name":"nn","Username":"ns","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1//306ad73427e262r9","Device
Name":"office"},{"Reg_user_name":"nn","Username":"nn","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1/e/306ad73427e262e7","Device
Name":"LAB lighting"}]
BUT in order to use the JSONobject and get the elements in it I need to give JSON like follows:
["Information":{"Reg_user_name":"nn","Username":"ns","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1//306ad73427e262r9","Device
Name":"office"},{"Reg_user_name":"nn","Username":"nn","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1/e/306ad73427e262e7","Device
Name":"LAB lighting"}]
I want to know that what I have to add in the PHP file to get that data with the added "information:" tag to it automatically using the above PHP file.
If you only want one index, you can change this
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
into this
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$json = array(
'information' => $rows,
);
print json_encode($json);
just add string index to the array the json encoder will automatically convert it
check this
while($r = mysql_fetch_assoc($sth))
{
$rows['information'][] = $r;
}
echo json_encode($rows);

Categories