$stmt = $db->prepare("SELECT * FROM friend JOIN user ON friend.uId=user.uId WHERE friend.friendId= ?");
$stmt->bind_param('s',$userId);
if($stmt->execute()){
$user = $stmt->get_result();
while ($obj = $user->fetch_object()) {
$friends[] = $obj;
}
echo json_encode($friends);
}
my above code produced an array
[{"uId":"2","firstName":"Gem","lastName":"Tang"},{"uId":"3","firstName":"James","lastName":"Lebron"}]
but I wish it could be 2 object instead.
You have an array of objects with length 2. Using JavaScript you can traverse it like this.
var o = [{"uId":"2","firstName":"Gem","lastName":"Tang"},{"uId":"3","firstName":"James","lastName":"Lebron"}];
for(var i = 0; i < o.length; i++) {
var row = o[i];
console.log(row.firstName);
}
in the while loop:
You could either use foreach:
$object = new stdClass();
foreach ($obj as $key => $value)
{
$object->$key = $value;
}
$friends[$obj['uId']] = $object;
or by the json functions:
$friends[$obj['uId']] = json_decode(json_encode($obj), FALSE);
Related
Apologize for the repeated question. Return multiple values from database with function. I tried executing code, the function returns one value, where I want all the values of id and name.
Database: id and name has 9 rows. Is there anything I was missing in my code.
function readdata() {
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
foreach ($sth as $s) {
$object = new stdClass();
$object->id = $s->id;
$object->name = $s->name;
return $object;
}
}
$rd = readdata();
echo $rd->id;
echo $rd->name;
May be something like this:
function readdata() {
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
$out = [];
foreach ($sth as $s) {
$object = new stdClass();
$object->id = $s->id;
$object->name = $s->name;
$out[] = $object;
}
return $out;
}
$rd = readdata();
//and here
foreach($rd as $obj){
echo $obj->id;
echo $obj->name;
}
This is more a suggestion than an answer. Why re-inventing the wheel? PDO already is capable of returning classes and also fetching all results into an array.
function readdata(PDO $db): array
{
$sth = $db->prepare('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
$sth->execute();
return $sth->fetchAll(PDO::FETCH_CLASS);
}
$objects = readdata($db);
$objects is now an array. Each element contains a stdClass object with each column name as property.
foreach($objects as $object) {
echo $object->id, PHP_EOL;
echo $object->name, PHP_EOL;
}
Your foreach loop intends to run through all values of the array $sth, but returns only with the FIRST one.
You can just return $sth to get the whole array, or build a new array and append to it:
$ret = array();
foreach ($sth as $s) {
...
$ret[] = $object;
}
and then
return $ret;
How
$arr = array ();
while ($obj = mysql_fetch_object($result))
$arr[] = $obj;
// add new key/value in same index
$arr['key'] = 'value';
echo json_encode ($arr);
In this construction not be result like I need
{
0 = {
author = 3;
id = 3;
reader = 3;
review = 4;
};
key = "value";
}
I need:
{
author = 3;
id = 3;
reader = 3;
review = 4;
key = "value";
}
It looks like your query is only returning 1 row, so you don't need the while loop.
First things first though, please don't use mysql_*. Look into MySQLi or PDO
This is what you want instead:
$db = new mysqli(/* host, user, pass, db */);
$result = $db->query("SELECT * FROM aTable LIMIT 1");
$arr = $result->fetch_assoc();
$arr['key'] = 'value';
Edit: Ima go ahead and force you to use mysqli...
Move the value-assigning code into the loop, if you need to add some key-value pair to each and every item of the resulting array:
$arr = array ();
while ($obj = mysql_fetch_object($result))
$obj->key = 'value';
$arr[] = $obj;
}
Let's say I have an array of objects.
<?php
$people = array();
$people[] = new person('Walter Cook');
$people[] = new person('Amy Green');
$people[] = new person('Irene Smith');
How can I search an object in this array for a certain instance variable? For example, let's say I wanted to search for a person object with the name of "Walter Cook".
Thanks in advance!
It depends of the person class construction, but if it has a field name that keeps given names, you can get this object with a loop like this:
for($i = 0; $i < count($people); $i++) {
if($people[$i]->name == $search_name) {
$person = $people[$i];
break;
}
}
Here is:
$requiredPerson = null;
for($i=0;$i<sizeof($people);$i++)
{
if($people[$i]->name == "Walter Cook")
{
$requiredPerson = $people[$i];
break;
}
}
if($requiredPerson == null)
{
//no person found with required property
}else{
//person found :)
}
?>
Assuming that name is a public property of the person class:
<?php
// build the array of objects
$people = array();
$people[] = new person('Walter Cook');
$people[] = new person('Amy Green');
$people[] = new person('Irene Smith');
// search name
$searchName = 'Walter Cook';
// ascertain the presence of the name in the array of objects
$isMatch = false;
foreach ($people as $person) {
if ($person->name === $searchName) {
$isMatch = true;
break;
}
}
// alternatively, if you want to return all matches into
// a new array of $results you can use array_filter
$result = array_filter($people, function($person) use ($searchName) {
return $person->name === $searchName;
});
hope this helps :)
well you could try this inside your class
//the search function
function search_array($array, $attr_name, $attr_value) {
foreach ($array as $element) {
if ($element -> $attr_name == $attr_value) {
return TRUE;
}
}
return FALSE;
}
//this function will test the output of the search_array function
function test_Search_array() {
$person1 = new stdClass();
$person1 -> name = 'John';
$person1 -> age = 21;
$person2 = new stdClass();
$person2 -> name = 'Smith';
$person2 -> age = 22;
$test = array($person1, $person2);
//upper/lower case should be the same
$result = $this -> search_array($test, 'name', 'John');
echo json_encode($result);
}
I am getting a json format like this
[{"service":{"title":"karthik","city":"chennai"}},{"service":{"title":"siva","city":"madurai"}}]
from code
$rt = array();
$rt["service"]["title"] = karthik;
$rt["service"]["city"] = chennai;
$t = array();
$t["service"]["title"] = siva;
$t["service"]["city"] = madurai;
echo json_encode(array($rt,$t));
but i need the same format of json result from this code
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id
FROM task");
while($row=mysql_fetch_array($a))
{
$jsonrow=new stdClass;
$jsonrow->title=$row['title'];
$jsonrow->city=$row['city'];
$jsonresponse=new stdClass;
$jsonresponse->service=$jsonrow;
}
echo json_encode(array($jsonresponse));
but the result actually i get from the above code is
[{"service":{"title":"Event Help","city":"Santa Fe"}}]
please someone help me on this issue.....
Use an array store all the values returned from the query
$array = array();
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id
FROM task");
while($row=mysql_fetch_array($a))
{
$jsonrow=new stdClass;
$jsonrow->title=$row['title'];
$jsonrow->city=$row['city'];
$jsonresponse=new stdClass;
$jsonresponse->service=$jsonrow;
$array[] = $jsonresponse;
}
echo json_encode(array($array));
you are overwriting $jsonresponse in your while loop, you should add this into array and json_encode this array
$response = array();
while( ... ){
...
$response[] = $jsonresponse;
}
echo json_encode($response);
try like this
$a=mysql_query("SELECT title,city,category,parentid,pay,task.id FROM
task");
$jsonrow=new stdClass;
$jsonresponse=new stdClass;
while($row=mysql_fetch_array($a)) {
$jsonrow->title=$row['title']; $jsonrow->city=$row['city'];
$jsonresponse->service=$jsonrow;
}
Why will my array have different output within the while loop, like it fetch all data from database in json, but once I declare the array outside of the while loop as commented out it gives output single row in json? Am I missing something basic or what? Thanks in advance
$query = "SELECT * from creative ORDER BY rand()";
$rs = mysql_query($query);
//$arr = array();
while ($obj = mysqli_fetch_object($rs)) {
$arr[] = $obj;
$cid = $arr -> id; //get id
}
if (isset($imei) && !empty($imei)) {
$add = array('delay'=>"1800000"); //Add Objects to JSON Encoded Array
$arr[] = $add;
echo json_encode($arr);
Have you tried array push?
$arr = array();
while ($obj = mysqli_fetch_object($rs)) {
//$arr[] = $obj;
array_push($arr, $obj);
//$cid = $arr -> id; //get id
}