My code is
$sql = 'select * from table;' $res = $connection->query($sql);
while($row = mysqli_fetch_row($res){'tackle output'};
to get an object
while($row = $res->fetch_object()){'tackle output'};
Question: what do I have to do to get an array of objects, so my output is thus
$data[$row[0]]= fetch_object();
try this one:
$data = array();
while($row = $res->fetch_object()){
$data[] = $row;
}
Use it like
$data = array();
while($row = $res->fetch_object()){
$data[$row->id] = $row;
}
may you want to fetch all
you can do this by
http://php.net/manual/en/mysqli-result.fetch-all.php
Related
So, using the Latte engine I can't seem to loop through every data row in my table. I can only get the first one and I've run out of ideas!
$query = $this->db->query("SELECT id,title FROM table");
$array = array();
while($fetch = $query->fetch_assoc()) {
$array = $fetch;
}
$Template["listing"] = $array;
Template:
{foreach $listing as $item}
{$item["title"]}}
{/foreach}
Simpliest solution is (if you don't need $array variable elsewhere):
$query = $this->db->query("SELECT id,title FROM table");
while($fetch = $query->fetch_assoc()) {
$Template["listing"][] = $fetch;
}
Instead of $array = $fetch, run $array[] = $fetch, in order to add more items.
What you're doing is overwrite the array in every loop.
$query = $this->db->query("SELECT id,title FROM table");
$array = array();
while($fetch = $query->fetch_assoc()) {
$array[] = $fetch;
}
$Template["listing"] = $array;
$query = $this->db->query("SELECT id,title FROM table");
$array = array();
while($fetch = $query->fetch_assoc()) {
$array[] = $fetch;
}
$Template = $array;
I need to print multiple database queries using json_encode(). I have this code below that outputs database records using json_encode. This works fine.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('SELECT username,firstname,lastname FROM user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
echo json_encode($data);
?>
I need to add another database query so that I can print them together using the same json_encode. Here is the database query that I want to add so that I can print them together using json_encode:
<?php
include('db.php');
$result = $db->prepare('SELECT price AS price1,goods AS product FROM provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
echo json_encode($data_pro);
?>
How can I accomplish this?
I think this might hit what you're looking for.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('select username,firstname,lastname from user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
$result = $db->prepare('select price as price1,goods as product from provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
// Combine both arrays in a new variable
$all_data['user'] = $data;
$all_data['pro'] = $data_pro;
echo json_encode($all_data);
I need to encode a table content to JSON in order to insert it into a file.
The output has to be as following :
{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}
Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.
The only thing I could manage for the moment is this :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
$index++;
}
echo json_encode($return_arr);
And here is the output I get :
[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]
Thanks a lot !!!
UPDATED
Working code :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}
echo json_encode($return_arr);
}
You were close. I noticed you want final output to be an object not an array, because the outer brackets are {} not []. So you need a different object type, and you need to use each row's name as the key for storing that row.
$return_obj = new stdClass();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
$return_obj->$name = [$row]; // for PHP < 5.4 use array($row)
}
echo json_encode($return_obj);
This loop is enough, to create the desired JSON:
$return_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
}
echo json_encode($return_arr);
I was working on it a lot of time and Create mash/mysql-json-serializer package.
https://github.com/AndreyMashukov/mysql-json-serializer
You can select Json_array of json_objects and etc. It support ManyToMany, oneToMany, manyToOne relations
SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res
<?php
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>
I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function
suppose i have a query
$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row=mysql_fetch_array($sql)){
$data = $row['data'];
}
$array = $data;
Now how can i get that each $data values out of while in an array() i.e $array
$array = array();
$sql = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_array($sql)) {
$array[] = $row['data'];
}
by adding each $row to array $data
for reference: http://php.net/types.array
Note that there is no such a thing as "while() array". There are just arrays only.
Your $data variable is being overwritten during each iteration. So you need to turn it into $data[] and $data should be declared at the top, or you can just use $array[] as the other answer suggests, not sure why you put in the $data variable in their in the first place.
You need to save each iteration object into a "new" object, so your code will look just like:
$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row=mysql_fetch_array($sql)){
$array[] = $row['data'];
}
please note the line:
$array[] = $row['data'];
References:
PHP Arrays
$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row=mysql_fetch_array($sql)){
$array[] = $row['data'];
}
further u can use
$array['data']
and u can also use mysql_fetch_assoc($sql) instead mysql_fetch_array($sql)