PHP - foreach function with array - php

Hi I have an error when I call a function.
"Warning: Illegal string offset 'id' in C:\xampp\htdocs\blog\posts.php
on line 28
2"
function:
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
return array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
Call:
require_once "functions.php";
$_posts = get_short_posts();
foreach($_posts as $_post) {
echo $_post['id'];
}

You know you return after the first iteration in the get_short_posts function right, so the foreach will not work as expected.
Try:
<?php
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
$return = array();
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
$return[] = array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
return $return;
}
?>
<?php
require_once "functions.php";
foreach(get_short_posts() as $_post) {
echo $_post['id'];
}
?>
Also, Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
$data [] = array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
return $data;
}
you return data, so the loop stops, save your data in a array and return that array like abive code

Your code is wrong it should be as below, assuming the query is returning data as mentioned.
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
$rows = array();
$return_data = array();
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
$data = array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
$return_data[] = $data;
}
return $return_data ;
}
require_once "functions.php";
$posts = get_short_posts();
foreach($posts as $key=>$val) {
echo $val['id'];
}

Related

Multidimensional array in PHP with keys

I making a script to monitorize data from some VPSs, which is being stored in a MySQL database.
$result = mysql_query("SELECT * FROM data");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array(
'id' => $row['id'],
'hostname' => $row['hostname'],
'loadavrg' => $row['load average']
);
}
I would like to separase data by hostnames so I can read it like the following example:
foreach($data['sitename.com'] as $d)
echo $d['loadavrg'];
I already tried with the following code (just for testing), but didn't work:
$result = mysql_query("SELECT * FROM data WHERE hostname='sitename.com'");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array(
'sitename.com' => array(
'id' => $row['id'],
'loadavrg' => $row['load average']
)
);
}
I'm just missing the right way and syntax to achieve it :X
Every element should be added as subarray of 'sitename.com':
while ($row = mysql_fetch_array($result)) {
$data['sitename.com'][] = array(
'id' => $row['id'],
'loadavrg' => $row['load average']
);
}
Try this,
while ($row = mysql_fetch_array($result)) {
$hostname = $row['hostname'];
$data[$hostname][] = array(
'id' => $row['id'],
'loadavrg' => $row['load average']
);
}

php datatable array results

I am trying to extract data from mysql database into a datatable using ajax, and php.
The code for my response.php file is below:
<?php
$result = mysql_query("select * from orders");
while ($row = mysql_fetch_array($result)) {
$data = array(
array(
'Name' => $row['jobnumber'],
'Empid' => $row['ID'],
'Salary' => $row['product']
)
);
}
$results = array(
"sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data
);
/*while($row = $result->fetch_array(MYSQLI_ASSOC)){
$results["data"][] = $row ;
}*/
echo json_encode($results);
?>
Why is this only returning one result in my front end table?
http://orca.awaluminium.com/test.php
link above shows table.
You're replacing value of $data instead of pushing new rows in an array.
Change the following line.
$data = array(
array(
'Name'=>$row['jobnumber'],
'Empid'=>$row['ID'], 'Salary'=>$row['product']
)
);
To
$data[] = array(
'Name'=>$row['jobnumber'],
'Empid'=>$row['ID'], 'Salary'=>$row['product']
);
Also put $data=array(); before string while() looop.
You have to do foreach
while ($row = mysql_fetch_array($result)){
foreach($row as $a)
{$data[] = array(
array('Name'=>$a['jobnumber'], 'Empid'=>$a['ID'], 'Salary'=>$a['product']),
);
}
}

Two queries mysql in one object json

I have two tables that I want to convert them to json like this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
but the result of my code is this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",}
,{
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
the code creates a new object to the array "people" and I want that are in the same object
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2['people'] = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2['people'],$row_temp);
}
array_push($json, $json2);
echo Json_encode($json);
How I can make the array is in the same object as the table "data"?
Many thanks
I think you may try this
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
// I think, you'll get a single row, so no need to loop
$json = mysql_fetch_array($result, MYSQL_ASSOC);
$json2 = array();
while ($row = mysql_fetch_assoc($fetch)){
$json2[] = array(
'name' => $row["name"],
'age' => $row["age"],
'city' => $row["city"]
);
}
$json['people'] = $json2;
echo json_encode($json);
Result of print_r($json) should be something like this
Array
(
[date] => 2013-07-20
[year] => 2013
[id] => 123456
[people] => Array
(
[0] => Array
(
[name] => First
[age] => 60
[city] => 1
)
[1] => Array
(
[name] => second
[age] => 40
[city] => 2
)
)
)
Result of echo json_encode($json) should be
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
If you do echo json_encode(array($json)) then you will get your whole json wrapped in an array, something like this
[
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
]
You were very close, but you want the People array to be a direct value of the outer array and you've wrapped it in an extra array.
Also, please note that the MySQL library you are using is deprecated. That means it will be removed from PHP in a future release. You should replace calls from the MySQL_* family of functions with either mysqli or pdo
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
$json['people'] = array();
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json['people'],$row_temp);
}
echo Json_encode($json);
You can make it work by waiting to use the key people until the very end when you join the two arrays. Up until then, just load the data into $json and $json2.
$json = array('date' => '2013', 'id' => '123456', 'year' => '2013');
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2 = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2, $row_temp);
}
$json['people'] = $json2;
echo Json_encode($json);

Get all data from sql php

I want to get all locations in table travel_location in mysql. This is my code
$select = $this->_db_table->select()->from(travel_location, array('*'));
$result = $this->_db_table->fetchAll($select);
if(count($result) == 0) {
throw new Exception('not found',404);
}
while ($row1 = mysql_fetch_array($result)){
$user_object = new Api_Model_User($row1);
$count = 1;
$json = array($json[$count] = array(
'travel_location_id' => $user_object->travel_location_id,
'city_id' => $user_object->city_id,
'user_id' => $user_object->user_id,
'location_name' => $user_object->location_name,
'description' => $user_object->description,
'longitude' => $user_object->longitude,
'latitude' => $user_object->latitude,
'created_time' => $user_object->created_time,
'updated_time' => $user_object->updated_time));
$count++;
}
It doesn't work. I print $row1 = mysql_fetch_array($result) and it returns false, so I think it's wrong because of this line. How can I fix it?
If you use fetchAll from Zend_Db_Table you get a Zend_Db_Table_Rowset as result.
Try this:
foreach ($result as $row) {
// $row should be a Zend_Db_Table_Row object
// you can cast to array
$rowArray = $row->toArray();
$user_object = new Api_Model_User($rowArray);
}
Read more about here and here

Displaying multiple rows in PHP array

I have a script I wrote to return records for cases out of the database. I am returning one record for my mysql query when there are actually two records. This is what I am returning:
{ "cases": [ {"name":"Test Case for App","number":"3846"}] }
I should see:
{ "cases": [ {"name":"Test Case for App","number": "2903"}, {"name":"Test Case 2","number": "2856"} ] }
Here is my source:
$sql = "select * from cases as c join contacts_cases as conc on c.id = conc.case_id where conc.contact_id = '1b360507'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_assoc($query);
$response = array(
'name' => $row['name'],
'number' => $row['case_number']
);
echo '{ "cases": [ ', json_encode($response), "] }";
If you are expecting more than one result you should try
if (mysql_num_rows($query) > 0)
{
$responses = array();
while($row = mysql_fetch_assoc($query)) {
$responses[] = array(
'name' => $row['name'],
'number' => $row['case_number']
);
}
echo '{"cases": ' . json_encode($responses) . '}';
}
You need to loop through all the rows, you're just getting one.
Also, don't try to build the JSON yourself. Make the array how you want then json_encode the entire thing.
$cases = array();
while ($row = mysql_fetch_assoc($query)) {
$cases[] = array(
'name' => $row['name'],
'number' => $row['case_number']
);
}
echo json_encode(array('cases' => $cases));

Categories