Insert to array new key/value php - php

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;
}

Related

Fetch multiple separated objects.

$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);

Array declared outside and inside loop gives different result in php mysql

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
}

Create new variable to store each result during While loop

I have a while loop that loops through 3 results and echo's these out in a list. It will always be 3 results.
Here is my current PHP:
while($row = sqlsrv_fetch_array($res))
{
echo "<li>".$row['SessionValue']."</li>";
// prefer to store each value in its own variable
}
However I'd like to store the $row['SessionValue'] value in each loop in a new variable.
So....
first loop: $i0 = $row['SessionValue'];
second loop: $i1 = $row['SessionValue'];
third loop: $i2 = $row['SessionValue'];
How would I achieve this with PHP?
Many thanks for any pointers.
$lst_count = array();
while($row = sqlsrv_fetch_array($res))
$lst_count[] = $row["SessionValue"];
You just need another variable that gets incremented:
$count = 0;
while($row = sqlsrv_fetch_array($res))
{
${i.$count++} = $row['SessionValue'];
}
You can do this have SUM of all value:
$total = array();
while($row = sqlsrv_fetch_array($res))
{
$total[] = $row["SessionValue"]
} $sumAll = array_sum($total);

First array element getting overwritten by the second when getting data from db using PHP

I have a few lines of code that start something like this:
$trailheads = array();
// Then a db call with a query. Then loop through the results.
// This gives a diff value every time, so here we are still ok
$trailhead->trailhead_name = $row['trailhead_name'];
// Before the look iteration ends, I do something like this:
array_push ( $trailheads , $trailhead );
// But I could have done this with the same result:
$trailheads[] = $trailhead;
And once I exit the loop, I do print_r and it shows that the second of the two rows returned by the query over-wrote the first.
Here is the full version of the loop:
while($row = mysql_fetch_assoc($trailhead_result))
{
$trailhead->trailhead_name = $row['trailhead_name'];
$trailhead->park_id = $row['park_id'];
$trailhead->trailhead_id = $row['trailhead_id'];
$trailhead->trailhead_description = $row['trailhead_description'];
$trailhead->parking = $row['parking'];
$trailhead->lat = $row['lat'];
$trailhead->lng = $row['lng'];
$trailhead->is_free = $row['is_free'];
$trailhead->parking_spots = $row['parking_spots'];
$trailhead->cost_details = $row['cost_details'];
$trailheads[] = $trailhead;
}
If that's your full loop, then one problem is that you're not initializing $trailhead inside the loop. Do this:
while($row = mysql_fetch_assoc($trailhead_result))
{
$trailhead = new trailhead();
$trailhead->trailhead_name = $row['trailhead_name'];
$trailhead->park_id = $row['park_id'];
$trailhead->trailhead_id = $row['trailhead_id'];
$trailhead->trailhead_description = $row['trailhead_description'];
$trailhead->parking = $row['parking'];
$trailhead->lat = $row['lat'];
$trailhead->lng = $row['lng'];
$trailhead->is_free = $row['is_free'];
$trailhead->parking_spots = $row['parking_spots'];
$trailhead->cost_details = $row['cost_details'];
$trailheads[] = $trailhead;
}
I have to assume that the object $trailhead is a class called trailhead. If it's not, use whatever class is correct in place of new trailhead().

add array element to row returned from sql query

I want to add an additional value into an array before passing it to json_encode function,
but I can't get the syntax right.
$result = db_query($query);
// $row is a database query result resource
while ($row = db_fetch_object($result)) {
$stack[] = $row;
// I am trying to 'inject' array element here
$stack[]['x'] = "test";
}
echo json_encode($stack);
If it's an array you can directly add a value:
$row['x'] = 'test';
$stack[] = $row;
if it's an object you can add another property:
$row->x = 'test';
$stack[] = $row;
if you want to keep the object and the extra value separated:
$data = array($row, 'x' => 'test');
$stack[] = $data;
but this does work.
$stack[] = $row;
$row->x = 'test';
How about something like:
$row['x'] = 'test';
$stack = $row;

Categories