return data from mysql and unserialize it - php

My SQL
$query = "SELECT value FROM oc_setting WHERE setting_id =7258";
$result = $this->db->query($query);
return $result->rows;
when I var_dump it show
array(1) {
[0]=>
array(1) {
["value"]=>
string(158) "a:1:{i:0;a:5:{s:8:"rss_link";s:11:"ddddddddddd";s:9:"layout_id";s:1:"2";s:8:"position";s:14:"content_bottom";s:6:"status";s:1:"1";s:10:"sort_order";s:1:"5";}}"
}
}
how can I unserialize array like this? cast to string first? I tried unserializ(var) but it say error coz it's an array.

PHP function unserialize (http://php.net/manual/en/function.unserialize.php) will help you.
unserialize($result[0]['value']);
will return you the array.

It seems you're using some PHP Framework (very similar to CodeIgniter one, but not sure).
There should be a function to retrieve exactly one (first) row from the result set.
Right now you're asking about a workaround which is not good. Usually DB drivers have a good interface to get how many rows/columns it took from query/view.
I usually use the following statement if I need go through the result array:
if ($result -> num_rows())
{
foreach ($result -> result_array() as $entry)
{
// do something
}
}

Related

Saving form values to an Object as attributes (Associative Array, PHP, PDO, lunk head)

I'm working on an AJAX CRUD and I cannot get the form values in the Assoc. array to save individually as object attributes for the MySQL query.
I am following enter link description here but instead of the mysqli I'm using PDO.
Not much of a php person and this is my first OOP use of PDO and JSON.
The vardump() shows the input text is there...
// get posted data
$data = json_decode(file_get_contents("php://input"), true);
// set event property values
$event=>mainTitle = $data->main-title;
$event->subTitle = $data->sub-title;
$event->eventUrl = $data->event-url;
And the dumps:
array(9) {
["main-title"]=>
string(15) "Test Main Title"
["sub-title"]=>
string(14) "Test Sub title"
["event-url"]=>
string(9) "Test URTL"
...
object(Event)#3 (11) {
["conn":"Event":private]=>
object(PDO)#2 (0) {
}
["table_name":"Event":private]=>
string(8) "tblEvent"
["mainTitle"]=>
int(0)
["subTitle"]=>
int(0)
["eventUrl"]=>
int(0)
...
try changing $event=>mainTitle to $event->mainTitle
You have passed a second argument to json_decode() what means you'd like to get an array instead of the object. So just work like with the array. Replace to $event->mainTitle = $data['main-title'];
I found the answer for part of my problem here: Handling-JSON-like-a-boss-in-PHP
json_decode() is able to return both an object or associative array.
//For an object:
$result = json_decode($string);
//For an Assoc. Array:
$result = json_decode($string, true);
What I struggled with is that the var_dump() returns almost exact result for the two. They indeed have to be the same type.
The second part of my problem that was more subvert was having hyphens in the object attribute names. I didn't find a reason why but for sake of clarity in my code I just removed them.

php json_encode return only first row of an array

I'm developing an Android application that makes some request to a server in which I have programmed a database. In the server I work with PHP to make query.
Now I wrote this code to make a query and to push the result into an array that I can use later in "Android part" by using java language.
This is my PHP code:
$query="SELECT * FROM $tbl_name WHERE user='$myusername'";
$res=mysql_query($query);
$posts = array();
if(mysql_num_rows($res)) {
while($post[] = mysql_fetch_assoc($res)) {
array_push($posts, $post);
}
}
echo json_encode(array('posts'=>$posts));
The problem is that when I try to get the result in java I can see only the first row of the result. I'm sure that I have more than 1 row because I tried to print mysql_num_rows($res) and the result was bigger than 1.
How can I fix this problem??
Edit.
Just to clarify. I make a call to my server in which I use php from Android AsynTask. In onPostExecute method I make something like this:
String res = result.toString();
where result is the JSONObject that I obtain from doInBackground method.
Maybe I'm doing error Here because all your solution give me always the first row of the query's result only.
You don't need to specify array here.
Change: while($post[] = mysql_fetch_assoc($res)) {
To: while($post = mysql_fetch_assoc($res)) {
You can always var_dump($posts) after while instruction and check if you get what you want.

Reference specific row's column value from array

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(){...}
}

PHP - Extract value from query array

Do you have to use a loop to extract the value from a query array.
Query:
$fetchRegion = Singlequery("SELECT region FROM regions WHERE id = :id LIMIT 1",
array('id' => $_GET['region']),
$conn);
This is my array:
array(1) {
[0]=>
array(1) {
["region"]=>
string(10) "South West"
}
}
I want to take the value and use it in another query, I didn't know if I had to use a foreach for example to get the value to use in my next query. The other stackoverflow questions that I saw used a loop
If i understand your question correctly and you want to acces to value then access it like so:
$fetchRegion[0]['region'];
You don't need to use foreach or any other loop since it will return at most one element because LIMIT 1 you used in query.
Using loop :-
foreach($fetchRegion as $v) {
$var = $v["region"];
}
or you get directly like:-
echo $fetchRegion[0]["region"];
No, there is no need to use a loop with that query because it will not return more than a single row. Instead, just check that you got a row back (it could return no results), and then use it.
If you're certain that your result is going to look like that, reset(reset($fetchRegion)) will give you the value 'south west'. It will behave badly if you don't get that exact format back though - for example, if the query does not return a row.

json encoding 2 dimension array

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/

Categories