php pdo json encode array print - php

When I pull data from the hello database, it just writes the first line, not the other lines, what could be the reason?
I did not know much about php json but did not get any results.
İD 88 NOT FOUND
**database print **
[{"title":"facebook","contact":"facebook adres"},
{"title":"twitter","contact":"twitter adres"}]
database data
id:87 [{"title":"facebook","contact":"facebook adres"},
{"title":"twitter","contact":"twitter adres"}]
id:88
[{"title":"instagram","contact":"instagram adres"},
{"title":"google","contact":"google adres"}]
database function
function menu($menu_title)
{
global $db;
$query = $db->prepare('SELECT * FROM menu WHERE menu_title = :menu_title');
$query->execute([
'menu_title' => $menu_title
]);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
$data = [];
foreach ($result as $key => $value) {
$data += json_decode($value['menu_content'], true);
}
return $data;
}
return null;
}
socialmedia foreach
<?php foreach (menu('sosyalmedya') as $key => $menu): ?>
<?= $menu['title'] ?><br>
<?= $menu['contact'] ?><br>
<?php endforeach; ?>

You're only returning the first element of each JSON array. Append the whole array to the result.
foreach ($result as $value) {
$data = array_merge($data, json_decode($value['menu_content'], true));
}
BTW, don't use SELECT * if you only want the menu_content column. Use SELECT menu_content.

Related

Retrieve data with foreach from return array function

I'm having troubles with my function and how to retrieve the data. Here is what i got.
public function getImages()
{
$array = array();
//Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
return $array;
}
}
Now I'm calling this function but i can not use foreach to access the array.
include "header.html";
include "autoload.php";
spl_autoload_register('my_autoloader');
$users = new User;
$users->getImages();
foreach ($users as $value) {
echo $value["username"];
}
What am I doing wrong? I'm only getting one result but there are many in my database. Or if i call the $array in foreach it says undefined.
A couple things. First, your function is only ever returning an array with one element in it. If you want to finish populating the array, don't return until after the loop:
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
And second, you're trying to iterate over the object which has the function, not the value returned from the function. Get the return value and iterate over that:
$userDAO = new User;
$users = $userDAO->getImages();
foreach ($users as $value) {
echo $value["username"];
}
You just need to put the return statement out of the while loop.
public function getImages() {
$array = array(); //Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
}

How do I build this array to output?

I have the following function which fetches some data from a MySQL table:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
var_dump($row);
};
echo $data
}
How can I push all the returned data into an array, where each member is indexed by a number?
Do I need to use echo or return at the end? They seem to have the same effect.
EDIT: Is this the correct way of returning results of the query? I am passing it to the front-end.
$questionData = $controller->readQuestion($quizType, $questionId);
return $questionData;
In general your function must looks like:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
return $query;
}
But, you have to look what is inside $query variable. If it is array - just return this array, if not - maybe it is some iterator, hence you have to check it and try to find method like toArray or something like that... Otherwise, you have to do something like:
$data = [];
foreach ($query as $row) {
$data[] = $row;
};
return $data;
Now you can use this function like:
var_dump(readQuestion($quizType, $questionId));
Take a look up here on how to secure your data.
Anyway, as I said in the comment you cannot use echo on an Array. And you can't do anything with the output of var_dump.
Change var_dump($row); for $data[] = $row;
and change echo $data; for return $data;
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
$data=$row;
};
return $result;
}

Unable to push all expected data to an array from collection using foreach loop in PHP

I am trying to add data to an array $result where each value is a string $idstring which will contain the employees ids like "999|888|777". The data is fetched from broadcastTbl collection from a MongoDB. I need to fetch each employee's corresponding details in a loop and push to $result. I am successfully fetching the data, but the trouble I am facing is in the below code where only one employees' data is getting pushed to the $result array.
$projection = array("broadcast_id" => 1, "employeeList" => 1);
$query = array("broadcast_id" => $broadcast_id);
$count = $this->collection->find($query)->count();
$cursor = $this->collection->find($query, $projection);
$result = array();
foreach($cursor as $row)
{
$idstring = trim($row["employeeList"]);
$idstring = preg_replace('/\.$/', '', $idstring);
$idarray = explode('|', $idstring);
foreach($idarray as $employeeId)
{
$this->EmployeeCollection = $this->db->EmployeesTbl;
$EmployeeCursor= $this->EmployeeCollection->find(array("EmployeeNumber" => $employeeId));
$EmployeeCursorCount= $this->EmployeeCollection->find(array("EmployeeNumber" => $employeeId))->count();
if($EmployeeCursor->count() > 0)
{
array_push($result,$EmployeeCursorCount);
foreach ($EmployeeCursor as $k => $row) {
array_push($result, $row);
}
}
else
{
array_push($result, array("datanotfound"=>1));
}
return json_encode($result);
}
}
You are returning too early.
Move return json_encode($result);
After the outer-most foreach loop.

codeigniter controller input Hebrew letters

I have a function in the controller that gets a string and then queries the database (via the model) for records that have this string as their name. This works fine with English but I have a problem when the input is in Hebrew. When I echo the string I see something like %D7%91 and the query fails.
All database tables entries are defined as utf8_general_ci.
My controller code:
function get_records_by_name($name)
{
echo 'searching for: '.$name.'</br>';
$keys = new DMkeys() ;
$query = $keys->get_keys();
$arr = array();
$count = 0;
foreach ($query->result() as $row)
{
if(stristr($row->name, $name) != FALSE)
{
$arr[] = $row->name;
$count++;
echo $row->name.'</br>';
}
}
$result = array('count' => $count, 'list' => $arr);
echo json_encode($result) ;
}
My model code:
function get_keys()
{
$query = $this->db->get('keys');
return $query;
}
Thanks,
Simon
You need to decode the variable before using it, try:
$name = urldecode($name);

Echo values of arrays?

I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}

Categories