PHP Inserting variables in array, but can't json_encode - php

Im with this for days, i tested if variables are being filled and they are, but i think somehow im not doing array right because 'echo json_encode($response)' is printing nothing. I also tried to replace variables in array to just random numbers and everything went fine, just with variables does work.
public function getPlaces() {
$places = array();
$stmt = "SELECT * FROM poi ";
$retval = mysqli_query( $this->conn, $stmt );
if ($retval) {
while($row=mysqli_fetch_array($retval)) {
$name = $row["name"];
$lat = $row["latitude"];
$lng = row["longitude"];
$desc = $row["descricao"];
$rating = $row["rating"];
$lm = $row["lm"];
$la = $row["la"];
$lv = $row["lv"];
$places[] = array('name'=> $name, 'lat'=> $lat, 'lng'=> $lng, 'desc'=> $desc, 'rating'=> $rating,
'lm'=> $lm, 'la'=> $la, 'lv'=> $lv);
}
return $places;
}else
return false;
}
The function is called here:
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array("error" => FALSE);
$places = $db->getPlaces();
if ($places != false) {
$response["places"] = $places;
echo json_encode($response);
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Error";
echo json_encode($response);
}

Instead of using associative array, use mysqli_fetch_object() to get the result set as object. You do not have to type all the field names if you use array_push().
while($row=mysqli_fetch_object($retval)):
array_push($places, $row);
endwhile;
Vardump the $places array to check the array.
E.g.
vardump($places); die;
or
print_r($places); die;

Did you notice the $ is missing before the $row variable on that line ?
$lng = row["longitude"];
This kind of missed (bad handled) Notice + Warning won't make your array.
Notice also that if your array is filled with some type of value it won't json_encode. Especially NaN values (thinking of this because of the nature of some fields like "rating" that could result in a NaN value).
Try by steps :
Dump your result for one line only with a LIMIT 1 in your SQL query to see if it works. Try only with one field...
Notice that $places = [];
is more optimized than a
$places = array();
Same with
$places[] = ['name'=> $name, ... ];

Related

Comparing GET response to a variable

I'm having trouble comparing the value returned from a get request to a variable. The get returns in a format that includes the row in the databases name along with the value. Since the variable does not have that "tag" too they don't compare correctly. Is there a way to compare them properly?
{"email":"[value]"}
Thats the format its returning in.
The value is in an array.
$app->get('/api/user_info/{email}', function($request, $response) {
require_once('dbconnect.php');
$email = $request->getAttribute('email');
$query = "select email from user_info";
$result = $mysqli->query($query);
$count = 0;
while($row = $result->fetch_assoc()){
$data[] = $row;
}
for ($i=0; $i < count($data); $i++){
if($data[$i] == ($email)){
$newResponse = $response->withjson($data[$i]);
return $newResponse;
//Should return email if they're the same
}
else {
$count += 1;
}
if ($count == count($data)){
$newResponse = $response->withjson("Email not found");
return $newResponse;
}
}
});
json_decode( '{"email":"[value]"}' ) will give you a standard PHP object with an "email" property.
I'm guessing a bit as to what GET key to use, but this should help you figure it out:
$var = json_decode( $_GET['email'] );
echo $var->email;

how to fetch all rows from mysql using mysqli_fetch_assoc and convert to JSON

I have tried to get all the rows from mysql table for that am using mysqli_fetch_assoc. While using this am getting only one row. I need to convert the resulting array into JSON.
$query = "SELECT * FROM db_category WHERE publish='1'";
$result = mysqli_query($c, $query) or die(mysqli_error($c));
$length = mysqli_num_rows($result);
if($length > 0)
{
$var['status'] = 'success';
while($obj = mysqli_fetch_assoc($result))
{
$var = array_merge($var, $obj);
$var1 = json_encode($var);
}
echo '{"slider":['.$var1.']}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"slider":['.json_encode($arr).']}';
}
Now the output for above code is,
{"slider":[{"status":"success","category_id":"12","category_name":"Books","publish":"1"}]}
Required output is,
{"slider":[{"status":"success","category_id":"1","category_name":"Apparel","publish":"1"},{"status":"success","category_id":"2","category_name":"Footwear","publish":"1"},{"status":"success","category_id":"3","category_name":"Furniture","publish":"1"},{"status":"success","category_id":"4","category_name":"Jewellery","publish":"1"}]}
How to solve this issue.
You can do it simply by json_encode() function. And you can also get all data into array, with mysqli_fetch_all() function :
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$jsonData = json_encode(array('slider'=>$data, 'status' => 'success'));
If you want to put 'status'=>'success' for each row, do it like this (before json_encode)
foreach($data as $key => $dataRow) {
$data[$key]['status'] = 'success';
}

I'm passing too many parameters

I'm passing a lot of parameters in a function
I want to know if its wrong what i am doing and if it is possible to put all those variables into an array and just call the array:
Here my function parameters:
function addjo($logo, $job_category, $job_name, $status, $localization, $job_type, $contract_type, $description)
My code to recognize all the variables.
if (isset($_POST['add_jo'])){
$job_category =$_POST['job_category'];
$description = $_POST['description'];
$job_name = $_POST['job_name'];
$logo = $_POST['logo'];
$status = $_POST['status'];
$localization = $_POST['localization'];
$job_type = $_POST['job_type'];
$contract_type = $_POST['contract_type'];
addjo($logo, $job_category, $job_name, $status, $localization, $job_type, $contract_type, $description);
}else{
$logo = NULL;
$job_category = NULL;
$job_name = NULL;
$status = NULL;
$localization = NULL;
$description = NULL;
$job_type = NULL;
$contract_type = NULL;
$check1 = NULL;
$check2 = NULL;
}
Is it possible to do something like this?
if(isset($_POST['mybutton'])){
array[](
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
);
function(callarrayhere);
else{
$var1 = null;
$var2 = null;
}
Thanks.
Since $_POST is already an array, just use it:
addjob($_POST);
And in addjob:
function addjob($input) {
// verify that array items are present and correct.
}
Exporting an array's values to individual variables is not only a waste of time and memory, but it also makes your code harder to read (where do these variables come from? It's not obvious they came from the same source array)
Of course it's possible:
if (isset($_POST['add_jo'])){
$a = array();
$a['job_category'] =$_POST['job_category'];
$a['description'] = $_POST['description'];
// and so on
$a['contract_type'] = $_POST['contract_type'];
addjo($a);
}
else
{
$a['job_category'] = null;
// and so on
}
And in function addjo you can display all values that way:
function addjo($a) {
foreach ($a as $k => $v) {
echo $k.' '.$v."<br />"
}
// or
echo $a['job_category'];
}
Yes it is possible to have an array as an argument to a function. Your syntax isn't quite right. This would do it:
function addjo($params){
echo $params['logo'];
echo $params['job_category'];
echo $params['job_name'];
}
Usage example:
$arr = array(
'logo' => $logo,
'job_category' => $job_category,
'job_name' => $job_name
);
addjo($arr);
You could also have default parameters for each of the array elements, or make them optional. See this answer for how to do that.

php function not returning all results from a MySQL query in a foreach

Hey guys I have a little issue with a function that retrieves data from a MySQL Database and then I iterate over the results with a foreach loop, checking a value to see if it is null and if it is, replacing it with another value.
The problem with this function is this, that after returning the data I'm only able to view one record retrieved from the database. Probably something simple but it's beyond me.
I would like to do this before passing it to the controller or view. Maybe this isn't possible with the foreach loop? What am I missing?
Here is an example of my code.
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
}
return $new_data;
}
Hopefully someone can help me with this? Thanks!
At the moment you are just returning the last data row. Change your code like this to return an array of all your rows from that function:
$rows = array()
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$rows[] = $new_data;
}
return $rows;
This way every row returned from the database will be added to an array named $rows. At the end you have to return your new array.
You are overwriting $new_data each iteration. Try this
$new_data = new stdClass
...
$all_data[] = $new_data;
Instead of checking for null value in the code, you could just use a IFNULL statement in the SQL query, this does separate the logic a bit but it might just be worth it in this case.
The function returns only the last row in the result because the new_data variable is overwritten in every step of your loop. Declare new_data an array at the start of your function and add rows as array elements
...
$new_data[] = new stdClass;
...
Each iteration of the foreach overwrites $new_data so in the end when the function returns, only the last fetched row will be returned. To return more than one row you could store all the rows in an array and then return the array in the end. It would look something like this:
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
$data = array();
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$data[] = $new_data;
}
return $data;
}
To be able to use this function you have to change the code that uses it to loop through the array of objects.

Serialize BEFORE the mysql_fetch_array?

I'm trying to use memcache but I'm stuck on a small part. I've got a function that gives in result an array of several things (most of them being strings), and one of them is the result of the mysql_query() function.
Here is how I am trying to unserialize:
$posts_count = my query;
/* MEMCACHE KEY GEN*/
$memcache_key = md5($posts);
$pagination = memcache_get($memcache, $memcache_key);
if($pagination==NULL) {
echo 'NOT CACHED';
$pagination = (the function that will call mysql_query)
//SAVE A SERIALIZED VERSION OF THE ARRAY
$memcache->set($memcache_key, serialize($pagination), 0, 3600);
}
else {
$pagination = unserialize($pagination);
}
//THIS IS ONLY THE RESULT OF mysql_query!!!
$posts = $pagination[result];
while($var = mysql_fetch_array($posts)) { ... stuffs here }
Any idea on how to "save" this result of mysql_query before the mysql_fetch_array? Or any idea how to use memcache to cache the whole while loop?
How about something like this:
$posts_count = "my query";
/* MEMCACHE KEY GEN*/
$memcache_key = md5($posts);
$pagination = memcache_get($memcache, $memcache_key);
if ($pagination == NULL) {
echo 'NOT CACHED';
$pagination = function_that_will_call_mysql_query();
// Create an array of all the results
$data = array();
while ($row = mysql_fetch_assoc($pagination['result'])) {
$data[] = $row;
}
$pagination['result'] = $data;
//SAVE A SERIALIZED VERSION OF THE ARRAY
$memcache->set($memcache_key, serialize($pagination), 0, 3600);
} else {
$data = unserialize($pagination);
}
// THIS IS ONLY THE RESULT OF mysql_query!!! (but now it's an array)
$posts = $pagination['result'];
while ($var = array_shift($posts)) {
// ... do stuff here
}

Categories