I am working on a feature of my website where I need to trigger an ajax call on the click of button. I am receiving data in this format:
Object {
name: "abc",
category_id: "1"
}
I want a result like this:
{
"list" : [
{
"name" : "xyz",
"category_id" : "1"
}, {
"name" : "abc",
"category_id" : "11"
}
]
}
my server side code is:
<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost","root","","test") or die(mysqli_error());
$name = $_GET['name'];
$sql = "SELECT * from test_search where name = '$name'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result)) {
$name = $row['name'];
$category = $row['category_id'];
}
$data = array("name" => $name , "category_id" => $category );
echo json_encode($data);
?>
Before, you were assigning $row array items to variables, and then not using them until after the loop. After the loop, you used those variables, but it would only have the last values. You must append your items to an array ('list') inside of your array and then json_encode() your result from the loop to get the desired effect.
<?php
$conn = mysqli_connect("localhost","root","","test") or die(mysqli_error());
$name = $_GET['name'];
header('Content-Type: application/json');
$sql = "SELECT * from test_search where name = '$name'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
$data_array = array('list' => array());
while($row = mysqli_fetch_array($result))
{
$data_array['list'][] = array("name" => $row['name'], "category_id" => $row['category_id'] );
}
echo json_encode($data_array);
?>
Untested code, apologies for any syntax errors.
I would also like to point out that your code is open to SQL injection attacks. Follow the link to the PHP Manual to learn more about these and how to prevent them.
You need to push $name and $category variables into another array - currently you're simply overriding those values in your while loop.
Do something like:
$list = array();
while($row = mysqli_fetch_array($result))
{
$list[] = array('name'=>$row['name'], 'category_id'=>$row['category_id']);
}
$data = array('list'=>$list);
echo json_encode($data);
Have a read about PHP arrays here - http://php.net/manual/en/function.array.php
Also before you jump straight to json_encode($data), try var_dump($data) see what you're working with.
You need to build the array in your while loop,
$data = [];
while($row = mysqli_fetch_array($result)) {
$data['list'][] = [
'name' => $row['name'],
'category' => $row['category']
]
}
echo json_encode($data);
Untested, but should give you what you need.
Related
I am new to PHP. I am trying to read MySQL with this PHP code.
....
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$rows = array();
$return = array();
while($row = mysqli_fetch_array($result)) {
$rows['UserId'] = $row['UserId'];
$rows['Nick'] = $row['Nick'];
$rows['Items'] = $row['Items'];
$rows['Skills'] = $row['Skills'];
...
$rows['LastUpdate'] = $row['LastUpdate'];
array_push($return, $rows);
}
header("Content-type:application/json");
echo json_encode($return);
Soon after runnning this code, it gets into infinite loop.
When I deleted the array_push line, it did not go into infinite loop.
So I guess that'd be the problem, but I can't find out why.
Is there something wrong with my code?
The MySQL database is in Amazon lightsail.
Please help me. Thanks in advance for any comments.
if you want to fetch all rows from database, and get data array of specific fields
<?php
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$filtered = [];
while($row = mysqli_fetch_all($result)) {
$filtered[] = [
'UserId' => $row['UserId'],
'Nick' => $row['Nick'],
'Items' => $row['Items'],
'Items' => $row['Items'],
'Skills' => $row['Skills'],
'Items' => $row['Items'],
'LastUpdate' => $row['LastUpdate'],
];
}
header("Content-type:application/json");
echo json_encode($filtered);
foreach record of your database information you are entering new data to rows array
while($row = mysqli_fetch_array($result)) {
// Logic of you application here
array_push($return, $row);
}
this pushes fetched row into rows array
how ever if you are not modifying database fetched information. you can fetch information as associative array and simply store it in variable. there will be no need for loop and storing in new array
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
header("Content-type:application/json");
echo json_encode($rows);
I want to have one array from these two tags so I can reference it through my client using either tag from the index
$query = "SELECT username,imgDefault from users"
$result = $sql->query($query);
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[]=$row;
}
$result->close();
$sql->close();
$str = implode(',', array_map(function($el){ return $el['username']; }, $rows));
$str1 = implode(',', array_map(function($el){ return $el['imgDefault']; }, $rows));
Desired Output Array
username:"d" imgDefault: "a", username:"b" imgDefault: "q", etc....
Im open to any other output that would help me identify the column value on an index
If I understood correctly what you're trying to do is to have the possibility to get a "username" based on a "imgDefault" OR to get a "imgDefault" based on a "username".
You should first get an associative array where the key is the username, and the value is the imgDefault:
$query = "SELECT username,imgDefault from users"
$result = $sql->query($query);
$associativeArray = array();
while($row = $result->fetch_assoc()) {
$currUsername = $row["username"];
$currImgDefault = $row["imgDefault"];
$associativeArray[$currUsername]= $currImgDefault;
}
$result->close();
$sql->close();
// $array will look like array("d" => "a", "b" => "q", ...);
Then you can look for a "imgDefault" based on a "username" using:
if (array_key_exists($theUsername, $associativeArray))
{
$theImgDefault = $associativeArray[$theUsername];
}
And you can look for a "username" based on a "imgDefault" using:
$theUsername = array_search($theImgDefault,$associativeArray);
Ok so I have a could similar to this.
<?php
$con = mysqli_connect("localhost", "user", "password", "DB");
if (mysqli_connect_errno()){
echo "failed to connect:" . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM DB");
$cars = while($row = mysqli_fetch_assoc($grab)){
"id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"];
}
json.encode($cars);
So I know that the while loop is a bit strange, but I need to know how I adjust the code so I can json encode the resulting variable, so I get an array of associative arrays.
I know this code wont work but how do I get it to work, I'm guessing its going to take a little more work, but am very new to coding and php.
Any help would be appreciated, thanks.
$cars = array();
while($row = mysqli_fetch_assoc($grab)){
$cars[] = array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"]);
}
json_encode($cars);
this is correct syntax and method
Close?
$the_array = array();
while($row = mysqli_fetch_assoc($grab)) {
$temp = array();
$temp['id'] = $row['Id'];
$temp['name'] = $row['Name'];
$temp['color'] = $row['Color'];
$the_array[] = $temp;
}
json_encode($the_array);
mysql methods are depreciated in PHP, try to use PDO extension.
Use the following
$grab = mysql_query($con, "SELECT * FROM DB");
$cars = array(); $i = 0;
while($row = mysql_fetch_array($grab))
$cars[$i++] = array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"]);
header('Content-Type: application/json');
json.encode($cars);
Excuse my language mistakes, I speak French.
I did some research on this site and elsewhere, but what I have found didn't solve my problem.
I am doing a site where people can post their stories. I'm working on a page where the author should be able to see his stories and chapters of each of them.
I do a query on two tables to get the titles of stories and chapters. I have a table "stories" in which there is the title and summary of each story (and other stuff like id and date of publication). And another table called "chapters", in which there is the title of each chapter and the id of the story to which they belong.
I would like to retrieve these items later in my html, to have something like this:
Story title 1
Chapter 1
Chapter 2
So I do a json_encode () but JSONLint said that the json I get is invalid. PHP is new to me, I began to learn so I'm probably not writing my code correctly.
Here is my code:
<?php
session_start();
require_once('connexion_db.php');
if($db=connect()){
$userID = $_SESSION['id'];
$arr = array();
$reqRecits = $db->query('SELECT titre, id FROM recits WHERE user_id = '.$userID.'');
$resRecits = $reqRecits->fetchAll(PDO::FETCH_ASSOC);
foreach ($resRecits as $r){
$recitID = $r['id'];
$recitTitre = $r['titre'];
$reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
$resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);
foreach ($resChapitres as $c){
$chapTitre = $c['titre_chapitre'];
}
$arr = array('titre'=>$recitTitre,'chapitre'=>$chapTitre);
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
}
}else{
echo "bdd non connectée.";
}
?>
I tested the method proposed here, but the result is worse.
I don't know what to do :(
Thanks for your help!
It seems like you'd want the inner loop to go more like this:
$chapTitre = array();
foreach ($resChapitres as $c){
$chapTitre[] = $c['titre_chapitre'];
}
So your resulting JSON would include all the chapter titles.
Also, as it stands, you're listing a series of unconnected JSON objects, which should probably be a single array to be a legal JSON object.
foreach ($resRecits as $r){
$recitID = $r['id'];
$recitTitre = $r['titre'];
$reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
$resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);
$chapTitre = array();
foreach ($resChapitres as $c){
$chapTitre[] = $c['titre_chapitre'];
}
$arr[] = array('titre'=>$recitTitre,'chapitre'=>$chapTitre);
}
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
Will collect them all and output as a list.
[
{
'titre': 'Title 1',
'chaptitre': ['Chapter 1', 'Chapter 2']
},
{
'titre': 'Title 2',
'chaptitre': ['Chapter 1', 'Chapter 2', 'Chapter 3']
},
]
<?php
session_start();
require_once('connexion_db.php');
if($db=connect()){
$userID = $_SESSION['id'];
$arr = array();
$reqRecits = $db->query('SELECT titre, id FROM recits WHERE user_id = '.$userID.'');
$resRecits = $reqRecits->fetchAll(PDO::FETCH_ASSOC);
$chapTitres = array();
foreach ($resRecits as $r){
$recitID = $r['id'];
$recitTitre = $r['titre'];
$reqChapitres = $db->query('SELECT id, titre_chapitre FROM chapitres WHERE recit_id = '.$r['id'].'');
$resChapitres = $reqChapitres->fetchAll(PDO::FETCH_ASSOC);
foreach ($resChapitres as $c){
$chapTitres[] = $c['titre_chapitre'];
}
$arr[] = array('titre' => $recitTitre, 'chaptitres' => $chapTitres);
}
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
}else{
echo "bdd non connectée.";
}
?>
> For Me this is Worked !
<?php
header('content-type: application/json');
date_default_timezone_set('Asia/Dhaka');
$DatabaseName = "";
$HostPass = "";
$HostUser = "";
$HostName = "LocalHost";
$db_connect = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
$userid = $_GET['id'];
$status = $_GET['status'];
$rows = array();
$datas = array();
$result = mysqli_query($db_connect, "SELECT id FROM drivers WHERE phone = '$userid'");
if ($result)
{
$row = mysqli_fetch_assoc($result);
$id = $row['id'];
$result = mysqli_query($db_connect, "SELECT `delivery_id` , `date`, `time` FROM `driver_orders` WHERE driver_id='$id' AND `status` ='$status'");
mysqli_set_charset($db_connect,"utf8");
while ($row = mysqli_fetch_assoc($result))
{
$d_id = $row['delivery_id'];
$data = mysqli_query($db_connect, "SELECT r_name,r_number,r_zone,r_address,amount FROM deliveries WHERE id = '$d_id'");
while ($row2 = mysqli_fetch_assoc($data))
{
$datas[] = array(
"r_name" => $row2['r_name'],
"delivery_id" => $row['delivery_id'],
"time"=> $row['time'],
"date"=> $row['date'],
"r_number" => $row2['r_number'],
"r_zone" => $row2['r_zone'],
"amount" => $row2['amount'],
"r_address" => $row2['r_address']
);
}
}
}
echo json_encode($datas);
?>
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());
}
}