I'm trying to get all data from table 1 in json format.
$arr = array();
$sql = "SELECT * FROM table1 ORDER BY price DESC";
$statement = $connect->prepare($sql);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $val){
$arr['id'] = $val['item'];
$arr['price'] = $val['price'];
}
echo json_encode($arr);
Result:
{"id":"item00125","price":"112.35"}
The problem is that I get only one record. Why isn't the foreach(){ not sending all the records?
Try:
foreach ($result as $val){
$arr[] = array(
"id" => $val['item'],
"price" => val['price']
);
}
That's because your array is being over-written every time.
Try this:
$i = 0;
foreach ($result as $val){
$arr[$i]['id'] = $val['item'];
$arr[$i]['price'] = $val['price'];
$i++;
}
echo json_encode($arr);
You got only one result because you override array key at every itration of loop
Just pass result set into json_encode Without using loop as
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
here your result variable get the all records but the problem is in the for each loop you are put the each value in position of ['id'] and ['price'] so every time for each loop put the value at that same position so means replace the value so you are getting the last value so I thing you have to put the every record in different different position like this:
$i = 0;
foreach ($result as $val)
{
$arr[$i]['id'] = $val['item'];
$arr[$i]['price'] = $val['price'];
$i++;
}
echo json_encode($arr);
I hope it works fine
Related
Here's my Query
$rows = $mydb->get_results("SELECT title, description
FROM site_info
WHERE site_id='$id';");
I get something like:
Title1 Desc1
Title2 Desc2
etc.
I want to put that data in array so I do:
$data = array();
foreach ($rows as $obj) {
$data['title'] = $obj->title;
$data['description'] = $obj->description;
}
When I do:
print_r($data);
I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.
You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.
So either do:-
$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
$data[$key]['title'] = $obj->title;
$data[$key]['description'] = $obj->description;
}
Or
$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
$data[$i]['title'] = $obj->title;
$data[$i]['description'] = $obj->description;
$i++;// increase the counter each time after assignment to create new index
}
For display again use foreach()
foreach ($data as $dat) {
echo $dat['title'];
echo $dat['description'];
}
If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");
If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);
When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.
echo "<ul>";
foreach ($rows as $obj) {
echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
}
}
echo "</ul>";
If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.
foreach ($rows as $obj) {
$data[] = ['title' => $obj->title, 'id' => $obj->id];
}
The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.
while($row = mysql_fetch_assoc($interst_list_select_result))
it's work one value to many value
I need to work without while loop but i need to all value in table.
how to i work this??
You can use a foreach loop.
$stmt = $db->prepare('SELECT * FROM tbl');
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row => $val){
echo $val['colname1'],' ',$val['colname2'];
}
If you need only the first result I think you can do this way
If( $row = mysql_fetch_assoc($interst_list_select_result)){
echo $row['you_column'];
}
if you need all
$rows = $stmt->fetchAll();
foreach ($rows as $row => $index){
echo $index['you_column'];
}
I am trying to get the matched rows from a table and save it in a Global Array so that I can use it in different functions.
But when I do print_r of that array it shows only last row.
Here is my code
function setCampoFeed()
{
echo $sql = "SELECT campofeed.tag,campofeed.registro,campofeed.valor FROM campofeed ".
"INNER JOIN registrofeed ON registrofeed.id = campofeed.registro ".
"WHERE registrofeed.feed='".$this->idFeed."'";
$result= $this->localDb->execute($sql);
$this->campoFeed= mysql_fetch_array($result))
}
So here campoFeed is the array that should have all the rows of the match, but now its just having the last row.
Thanks in advance
Use
$this->campoFeed[] = mysql_fetch_array($result);"
insted of
$this->campoFeed= mysql_fetch_array($result);
You will get all data in array
Try this one if it works for you..
$resultArray = array();
$campoFeed = array();
$resultArray = mysql_fetch_array($result);
foreach($resultArray as $key => $value){
$campoFeed[$key] = $value;
}
print_r($campoFeed);
Use this
$mergedArray=array();
while($data= mysql_fetch_array($result)) {
$final_array = unserialize($data['data']);
$mergedArray=array_merge($mergedArray,$final_array);
}
array_unique($mergedArray, SORT_REGULAR);
I have this array:
$cust = xtc_db_query("SELECT customers_id FROM orders");
$customers = xtc_db_fetch_array($cust);
When I try to display every single record I get only the first one:
foreach ($customers as $v) {
echo "ID: $v.\n <br>";
}
I tried setting the array manually and then it works fine:
$customers = array(1, 2, 3, 17);
Your $customers array will only ever contain one value (the last result from the query). You'll need to use a while loop:
$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust))
{
// Use $customers here.
}
$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust)){
echo "ID: $customers[customers_id].\n <br>";
}
xtc_db_fetch_array will return one record in every iteration.
To get all the records, you'll have to put xtc_db_fetch_array($cust) in while loop like below.
$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust)){
print_r($customers);
}
I am querying like this, in snippet below 1st loop takes column names and second loops push values in another array(i know this may not be an optimal way but this is what came in my mind and is solving my task). The problem is
$results = '';
$dataArray = array();
$columns_array = array();
$dataArray = array();
$results = mysqli_query($mysqli, ("SELECT
DISTINCT states_drg.`Provider State`,
SUM(states_drg.`Total Discharges`) AS discharges
FROM states_drg
GROUP BY states_drg.`Provider State`")
);
$columns_names = mysqli_fetch_assoc($results);
foreach ($columns_names as $key => $value) {
array_push($columns_array, $key);
}
array_push($dataArray, $columns_array);
foreach ($results as $result) {
array_push($dataArray, mysqli_fetch_row($results));
}
print_r($dataArray);
echo json_encode($dataArray, JSON_NUMERIC_CHECK);
exit;
);
Query runs absolutely fine in query browser, but when I take dump of print_r($dataArray); I get only 26 records where as I have around 51 records in total if I run the Query in Query Browser.
You're using mysqli totally wrong.
foreach($results as $result)
is NOT how you fetch data from a query result. You should have
while($row = mysqli_fetch_assoc($result)) {
$dataArray[] = $row;
}
And not to mention the multiple syntax errors in your pasted code...