I have read a-lot of answers on this but they don't seem to be working.
I have the following code:
$amountoflikes=mysql_query("SELECT * FROM `uc_likes` WHERE `dwable` = '372'");
This returns the following:
If I wanted to echo the value of dwable in the 2nd row for instance (not involving the initial query).
I've tried:
while($row3 = mysql_fetch_assoc($amountoflikes)){
$json[] = $row3;
}
echo json_encode($json);
But this returns null.
I'm currently using PHP 5.5 (native).
I'm not using MySQLi or MySQL PDO.
Can someone tell me where I'm going wrong. Ideally I'd prefer not to use a loop but I don't know if that's possible.
Thanks!
Try declaring $json as an array above the while:
$json = array();
declare your array as follows
$json = array();
and see if you have results before your result
if ($amountoflikes)
{
while(){...}
}
Related
This is the data that i need to extract like example profile_contact_numbers
so the output will be +639466276715
how can i do it in php code??
any help will do regards
a:2:
{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}
I'm not sure 100% this can go into an array but try the unserialize function
$json_resp = {your values};
$array[] = unserialize($json_resp);
To check if it has gone into an array print_r on $array.
Read this link if the code above doesn't work
http://php.net/manual/en/function.unserialize.php
I have managed to fix it
$serialized = array(unserialize('a:2:{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}'));
var_dump($serialized);
use code :
$var = preg_split('["]','{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}');
echo $var[1].'='.$var[3]; // profile_contact_numbers=+639466276715
echo $var[5].'='.$var[7]; // profile_position=Courier
I'm having a difficult time appending each element in an array I have in PHP for multiple OneSignal tags. Here is the result of my current JSON encoded array:
[{"value":"email#address.com"},
{"value":"email#address.com"},
{"value":"email#address.com"}]
Desired output:
[{"key":"user_email","relation":"=","value":"email#address.com"},
{"key":"user_email","relation":"=","value":"email#address.com"},
{"key":"user_email","relation":"=","value":"email#address.com"}]
Here is my current PHP code:
$jsonData = array();
$allStaffInit = mysql_query("Select * from users");
while ($staffrow = mysql_fetch_object($allStaffInit)){
$jsonData[] = $staffrow;
}
echo json_encode($jsonData);
Any help is greatly appreciated! Thanks!
Try replacing
$jsonData[] = $staffrow;
with
$object = new stdClass();
$object->key = "user_email";
$object->relation = "=";
$object->value = $staffrow->value;
$jsonData[] = $object;
I am typing this in a browser, so cannot test, but you get the idea (if you don't get the idea, ask in comments :)
If you must use the mysql_ functions, you don't need to manually construct an object or array, just get the result set as an array and use that.
while ($staffrow = mysql_fetch_assoc($allStaffInit)){
$jsonData[] = $staffRow;
}
But I seriously recommend you at least upgrade to using the mysqli extension instead. You won't really have to adjust your code much.
http://php.net/manual/en/book.mysqli.php
I am storing a JSON array of data within a row in a database and attempting to retrieve the array in order to use in a foreach loop.
The code below is the code that I will be using for the foreach loop, but I am having some troubles actually retrieving the data, using PDO, as needed to be used.
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $data){
echo $data['id'];
}
The problem I am having is retrieving the array to put into $data using PDO. Currently I have this query and code, the output for which is below.
$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
$statement->bindParam(':c_s', $c_s);
$statement->execute();
$data = $statement->fetchAll();
$result = json_encode($data, true);
return $result;
Mixed with the following code to show the array:
foreach ($result as $key) {
echo $key['id'];
}
print_r($result);
die();
This gives an error for the for each, and outputs the array (unusable) as following:
[{"gp":"[{\"id\":\"H592736029375\"},{\"id\":\"K235098273598\"},{\"id\":\"B039571208517\"}]","0":"[{\"id\":\"H592736029375\"},{\"id\":\"K235098273598\"},{\"id\":\"B039571208517\"}]"}]
Being as the first segment of code I have I can use the data as I needed I'm just in need of some guidance of how to correctly get the array from the database to then be used in the foreach.
I'm aware that I'm currently using json_encode instead of json_decode, using json_decode gives the following error:
Warning: json_decode() expects parameter 1 to be string, array given
Suggestions for my errors would be much appreciated
fetchAll() returns an array of rows, not the single field you expect:
$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
$statement->bindParam(':c_s', $c_s);
$statement->execute();
$rows = $statement->fetchAll();
$data = $rows[0]['gp'];
$result = json_decode($data);
You are expecting $data to be a string while it's an array. Either use $statement->fetchColumn() to retreive a single field or use json_decode($data['gp'])
Other then that, I'm not exactly sure why you are looping over a json_encoded array, you can't do that.
json_encode() formats variables for javascript object notation.
json_decode() loads variables from strings(READ: string, not array) in the javascript object notation.
To make it even clearer:
use json_encode() to insert data in mysql.
use json_decode() to put back a column to their corresponding php variable/state.
I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/
I am having a problem with the last comma when I am using PHP echoing JSON Array to android
Here is my code
If ($commentResult>0)
echo "[";
{
while ($row = mysql_fetch_array($commentResult)) {
echo json_encode($row).",";
}
echo "]";
Android can't read this, it printed out JSONException:Vale at 3 is null
Why are you trying to re-invent the wheel? If you want to give an entire array then put json_encode over the entire array instead of trying to manually build it.
$comments=array();
if($commentResult>0){
while($row=mysql_fetch_array($commentResult)){
$comments[]=$row;
}
}
echo json_encode($comments);
*Also, a side tip, don't use mysql_ functions. Instead use PDO or mysqli, which are better supported and get you rid of this whole while($row) business.*
The way you form you json is really strange. Don't know if it's an issue but you can try it in a more clean way:
if ($commentResult) {
for ($data = array(); $row = mysql_fetch_array($commentResult); $data[] = $row);
echo json_encode($data);
}
What ever JSON you are generating using PHP, Just verify that in http://jsonlint.com/. if output is wrong it wont validate other wise its OK from PHP side.