I need help in json response in php - php

Here is my code:
<?php
while ($row = mysqli_fetch_assoc($searching_user))
{
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"] = $salon_name;
echo json_encode($response);
}
?>
after this I'm getting the response in this format
{"error":false,"service_name":"Mike
salon"}{"error":false,"service_name":"Michel salon"}
{"error":false,"service_name":"Michel salon"}{"error":false,"service_name":"Mike Salon"}
{"error":false,"service_name":"Etta Salon"}
I simply want this response like this
[ {"error":false,"service_name":"Mike
salon"},{"error":false,"service_name":"Michel
salon"},{"error":false,"service_name":"Michel
salon"},{"error":false,"service_name":"Mike Salon"},
{"error":false,"service_name":"Etta Salon"}]
Kindly help me to get a proper response form for json .
Thanks

Don't json_encode() the single results, but put them into an array and finally json_encode() that:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response[] = [
'error' => FALSE,
'service_name' => $salon_name,
// you may want to add more attributes here...
];
}
echo json_encode($response);
I personally suggest to shorten this:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$response[] = [
'error' => FALSE,
'service_name' => ucfirst($row['service_name']),
'salon_id' => $row['id'],
'salon_address' => ucwords($row['address']),
'salon_area' => ucwords($row['area']),
'salon_city' => ucwords($row['city']),
'salon_specialty' => ucwords($row['specialty']),
'img' => $row['image_url'],
];
}
echo json_encode($response);

You are trying to encode single results, Try to create a array will all the results and encode it out side the loop.
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"]=$salon_name;
// Added this line
$responses[] = $response;
}
//Encode all results
echo json_encode($responses );

Related

Update query laravel return false result and nothing error show why?

i'm working with laravel project, and i have an issue that is update query result return false value if i update with the same data, how to solve this? do i have to validate first before run the query and send a notification that the data is the same?
well this is my codes
public function update(Request $request)
{
$kamar_id = $request->input('kamar_id');
$title = $request->input('title');
$content = $request->input('content');
$keyword = $request->input('keyword');
$description = $request->input('description');
$prolog = $request->input('prolog');
$path = $request->input('path');
$sort = $request->input('sort');
$status = $request->input('status');
$type = $request->input('type');
$user_id = $request->input('user_id');
if (empty($request->input('path'))) {
$path = serialize(array('data/def.png'));
}else{
$path = serialize(explode(',', $request->input('path')));
}
$data = array('title' => $title,
'content' => $content,
'keyword' => $keyword,
'description' => $description,
'prolog' => $prolog,
'path' => $path,
'sort' => $sort,
'status' => $status,
'type' => $type,
'user_id' => $user_id);
// echo($kamar_id);
$update = Kamar::where('kamar_id',$kamar_id)->update($data);
if ($update) {
$response['status'] = 1;
}else{
$response['status'] = 0;
}
return response()->json($response);
}
thanks for helping me
Laravel Eloquent Update method returns true if anything updated in database from your query and return false if nothing is updated in database from your query.
refer:
https://laravel.com/docs/5.8/eloquent#updates
!nullTry
$update = Kamar::where('kamar_id','=',$kamar_id)->first();
if (!null($update))
{
$update->title = $title;
$update->content = $content;
$update->keyword = $keyword;
$update->description = $description;
$update->prolog = $prolog;
$update->path = $path;
$update->sort = $sort;
$update->status = $status;
$update->type = $type;
$update->user_id = $user_id;
$update->save();
$response['status'] = 1;
}
else
{
$response['status'] = 0;
}
Try using this
$kamarObj = new Kamar();
$kamarData = $kamarObj->find($kamar_id);
$result = $kamarData->update($data);
You can force updated_at column to be updated (or you can create this column if you don't have). So the query will be always updated.

Loop return one result in conditioner query

I am trying to fetch data from database in code-igniter .Bur this loop return only one loop .
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
You need to define $userdatas=array(); outside the loop. It is inside the loop that's why it overrides the data and returns the last record.
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
$userdatas = array();
foreach($userchatData as $key => $userdata){
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] =$userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
Hope this will help you :
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[$key]['chat_id'] = $userdata['chat_id'];
$userdatas[$key]['chat_from'] = $userdata['chat_from'];
$userdatas[$key]['created_date'] = $userdata['created_date'];
}
/*print_r($userdatas); output here*/
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
}
echo json_encode($data);

php json data return jquery

Looking for a best solution:
$.getJSON("InsertData.php", {fullName:val1, course_id:course_id, occupation:val2}, function(data) {
$.each(data, function(i, user) {
//alert(user.aryA.status);
if(user.aryA.status == 'true'){
currentPosition = 2;
checkData();
nextSlide();
}else{
nextSlide();
}
});
})
Here is php code:
mysql_select_db("db", $con);
$Query="SELECT * from table WHERE fullName='".$fullName."' and course_id='".$cid."'";
$result = mysql_query($Query);
$totalRecords = mysql_num_rows($result);
if($totalRecords) {
while ($row = mysql_fetch_array($result)) {
$returnData[]=array( //for Json data array
'userName' => $row['fullName'],
'aryA' => array(
'status' => $row['status']
)
);
}
}
if(!$totalRecords) {
$insertQuery="INSERT INTO table (fullName,course_id,occupation) VALUES ('".addslashes($fullName)."','".addslashes($cid)."','".addslashes($d3)."')";
$result1 = mysql_query($insertQuery);
}else{
if($stat == "true"){$value = 1;}
}
mysql_close($con);
echo json_encode($returnData);
So In first case when I hit the php through jquery it saves data in database but give me error or length. Because $returnData is empty. Is there a way if $totalRecords is false, how to send json_encode to say there is no data or any value through json_encode to my jQuery function.
Thanks in advance.
Just setup an else statement, and add a 'success' key to your array:
if($totalRecords){
while ($row = mysql_fetch_array($result)) {
$returnData[]=array( //for Json data array
'success'=>'true',
'userName' => $row['fullName'],
'aryA' => array(
'status' => $row['status']
)
);
}
}else{
$returnData = array('success'=>'false');
}
Then check the value of 'success' in your jQuery.
Also, you really shouldn't be using mysql_*.
$returnData = array(); //add this
$totalRecords = mysql_num_rows($result);
if($totalRecords) {
while ($row = mysql_fetch_array($result)) {
$returnData[]=array( //for Json data array
'userName' => $row['fullName'],
'aryA' => array(
'status' => $row['status']
)
);
}
}
else
{
$returnData[] = 'no Record'; //add this
}

Php JSON Response Array

I have this php code. As you can see i query a mysql database through a function showallevents. I return a the $result to the $event variable. With the while loop i assign the values that i get from event to a response array and every time the loop happens the rows are stored in the data array. Surely i am failing somewhere because despite i am getting a correct number of responses all the values that i get at json are "null". Also it tells me something about JSONarray cannot be converted to jsonobject
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'showallevents')
{
// Request type is show all events
// show all events
$event = $db->showallevents();
if ($event != false)
{
$data = array();
while($row = mysql_fetch_assoc($event))
{
$response["success"] = 1;
$response["uid"] = $event["uid"];
$response["event"]["date"] = $event["date"];
$response["event"]["hours"] = $event["hours"];
$response["event"]["store_name"] = $event["store_name"];
$response["event"]["event_information"] = $event["event_information"];
$response["event"]["event_type"] = $event["event_type"];
$response["event"]["Phone"] = $event["Phone"];
$response["event"]["address"] = $event["address"];
$response["event"]["created_at"] = $event["created_at"];
$response["event"]["updated_at"] = $event["updated_at"];
$data[]=$response;
}
echo json_encode($data);
}
else
{
// event not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Events not found";
echo json_encode($response);
}
}
else
{
echo "Access Denied";
}
}
?>
the DB_Functions.php
<?php
class DB_Functions
{
private $db;
//put your code here
// constructor
function __construct()
{
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct()
{
}
/**
* Select all events that are after yesterday.
*/
public function showallevents()
{
$result = mysql_query("SELECT * FROM events WHERE date >= CURDATE()");
return($result);
}
}
?>
ok the code that helped me put all data into an array was this
$data = array();
while($row = mysql_fetch_assoc($event))
{
$response["success"] = 1;
$response["event"]= $row;
$data[]=$response;
}
echo json_encode($data);
You've merged two independent pieces of code and wound up with a mess whose result is unclear.
You can create an associative array in two ways:
$array = (key=>value, key2=>value2);
You can also use:
$array[key]=value;
$array[key2]=value2;
Note that both 'key' and 'value' are simply variables; you can use strings there, or pass in a variable from someplace else.
When doing similar things, I use the following approach:
$response["success"] = 1;
$response["uid"] = $event["uid"];
$response["event"]["date"] = $event["date"];
$response["event"]["hours"] = $event["hours"];
$response["event"]["store_name"] = $event["store_name"];
$response["event"]["event_information"] = $event["event_information"];
$response["event"]["event_type"] = $event["event_type"];
$response["event"]["Phone"] = $event["Phone"];
$response["event"]["address"] = $event["address"];
$response["event"]["created_at"] = $event["created_at"];
$response["event"]["updated_at"] = $event["updated_at"];
$data[]=$response;
What is your $response variable?
In PHP to create associative arrays, you use => and not =
for example:
$array = ('key1' => 'value1', 'key2' => 'value2');
if you just want to return all the arrays, can you use mysql_fetch_assoc in stead of mysql_fetch_row?
if ($tag == 'showallevents')
{
// Request type is show all events
// show all events
$event = $db->showallevents();
if ($event != false)
{
$data = array();
while($row = mysql_fetch_assoc($event))
{
$data[] = $row;
echo json_encode($data);
}
else
{
// event not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Events not found";
echo json_encode($response);
}
}
else
{
echo "Access Denied";
}
}
?>

Codeigniter result array return only one row

Am trying to encode an array to json for use with jquery.
This is the function from my model
function get_latest_pheeds() {
$this->load->helper('date');
$time = time();
$q = $this->db->select("user_id,pheed_id,pheed,datetime,COUNT(pheed_comments.comment_id) as comments")
->from('pheeds')
->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
->group_by('pheed_id')
->order_by('datetime','desc')
->limit(30);
$rows = $q->get();
foreach($rows->result_array() as $row) {
$data['user_id'] = $row['user_id'];
$data['pheed_id'] = $row['pheed_id'];
$data['pheed'] = $row['pheed'];
$data['comments'] = $row['comments'];
$data['datetime'] = timespan($row['datetime'],$time);
}
return $data;
}
And this is from my controller
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
echo json_encode($data);
return false;
}
}
It returns only 1 row from the database when I run the code in the browser.
Please help me out
You are overwriting data in every iteration !!
Use something like
$data[] = array(
'user_id' => $row['user_id'];
'pheed_id' => $row['pheed_id'];
'pheed' => $row['pheed'];
'comments' => $row['comments'];
'datetime' => timespan($row['datetime'],$time);
) ;
This is good but your syntax should be 'user_id' => $row['user_id'], for each element of the array

Categories