How to merge some static data with json encode mysql array data? - php

I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.

try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.

mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.

Related

Pass values to an other entity Symfony

What I need to do is to export as as .csv a list of a lot of different values inside different entities. I need each reference created at a certain date with related values.
What I did was first, find all the objects by date and put them in an array.
$parcelRepo = $this->getDoctrine()->getRepository(Parcel::class);
$dateToday = new \DateTime("now");
$parcels = $parcelRepo->findBy([
'date_add' => $dateToday
]);
Then, in a foreach loop, I find the values that relates to each parcel entity. This is where I have a problem, I don't understand how to access the values which are not located in the same table as my first parcel entity.
I need to not use SQL as well.
Here is the code where I get the "Only variables should be passed by reference" error.
$array = [];
foreach ($parcels as &$p) {
$array.array_push(
$p->getDeliveryOrder()->getProduct()->getAccount()->getCoclico(),
"1",
"",
$p->getDeliveryOrder()->getUser()->getLogin(),
$p->getDeliveryOrder()->getProduct()->getCode(),
$p->getInternalReference(),
$p->getDeliveryOrder()->getProduct()->getCode()+"0"+$p->getNumber(),
"121",
$p->getName(),
$p->getAddress4(),
$p->getAddress1(),
$p->getAddress2(),
$p->getAddress3(),
"téléphone", //TODO
$p->getPostalCode(),
$p->getCity(),
\DateTime::createFromFormat('Ymd',$dateToday),
"",
"",
"0"
);
}
I think I need to use QueryBuilder but was wondering if there was any other way to do what I need since QueryBuilder is close to SQL (from what I understand).
Also, as I need to export each foreach values in one line, I need a multidimensional array. However I did not look into this issue since I can't even get the values I need.
So the issue comes from
$array.array_push(
this code actually merges $array and array_push() returning value, array_push() first parameter should be the array ( which is sent through reference) you want to push in, and because you are actually sending a value and not a variable, this error appears.
Here is the documentation for array_push https://www.php.net/manual/ro/function.array-push.php
so it should actually be
array_push($array, ...);
But as Ricardo left you a comment, this code is not really necessary, you can get the formatted data like this from a query, chaining multiple relation calling like:
$p->getDeliveryOrder()->getProduct()->getAccount()->getCoclico()
is not really desirable, but if you think you can't do that then the fix is just to write array_push correctly.

How to make serialized array to save in database

I want to Save Serialized array in Mysql Database.
I want final result when save value in database looks like in below format:
a:1:{i:5;s:2:"2,";}
Please provide solution starting from how to make this kind of array and simple sql query (insert or update query).
Below is the code which i used:
<?php
$a = array (
'5' => '2,'
);
$b = serialize($a);
?>
and i use $b variable in sql query. But my data not save in my expected format.
Just to give you simple directions. Youll need to parse data from wherever you are passing from in Json format (object or an array). Then in php use json_encode
And as # Richard said youll need to grasp these on your own then post some code youve tried but probably fails.

When using json_encode to display the contents of a select query, how to name objects?

Disregarding security issues (for now)
I am using json_encode to display the contents of a select query.
I used:
$sql= {query code};
// created a temp array to hold data and an array for all the results
$resultArray = array();
$tempArray = array();
// looped through every object in the result set
while ($row = $result->fetch_object());
// added it into the results array
$tempArray = $row;
array_push($resultsArray, $temparray);
// encoded the array to a json format
echo json_encode($resultArray);
Question: My objects don't have names, so it makes it difficult for me to write any code that could read the results and display them. How do I name the objects? Is it an entry I could add into the table (let's say in a case of different names I could give each object)
You should try to build the array/object structure you want in PHP. That way when you json_encode it, you'll know what it looks like and it will be what you want.
Try:
echo json_encode(array('people' => $resultArray));
In fact this should not work at all. Casting PDO (or MySQLi, as mentioned in comment) objects to JSON. You should use fetch_assoc instad, that would return associative array that could be put directly in JSON structure.

How to Access Array

I am still a beginner in PHP and MySQL and have come across a complicated array I need some help with.
So far the arrays I have worked with are fairly flat, i.e. 1 row of data with multiple fields, say for example a result based on a single address, so line1, line2, line3, town, etc.
I am now dealing with an external api that returns the following results in xml
{"result":
{
group1 [{"fieldname1":"fieldresult1", "fieldname2":"fieldresult2}]
group2 [{"fieldname3":"fieldresult3", "fieldname4":"fieldresult4}]
}
"message":"OK",
"success":true}
My question is how do I access each of the results,
I am planning on using a foreach statement, and will be calling the result $xmlarray.
I then want to define strings such as $field1, $field2, but not sure how to do this when it seems to be quite a deep array, I am guessing something like:
$field1 = $array([0]["field2"];
As I say, I need someones help just to give me a brief overview here, thanks
This content of you posted Data looks like JSON to me...
so you could try some like
$json = json_decode($array);
than you could go for
$field1 = $json['group1']['fieldname1'];
and so on.
source
This is not XML. It is json. Use json_decode() for this.
$data = json_decode($response); //$response is the response you are getting from the api.
var_dump($data);
$data will contain the response. The you can access them easily.json_decode()

build SQL statement from json encoded string php

Welcome Stackoverflow nation ! I'm trying to decode json encoded string into SQL statement withing php.
Lets say I've such a json encoded string =>
$j = '{"groupOp":"AND","rules":[{"field":"id","op":"cn","data":"A"},{"field":"i_name","op":"cn","data":"B"}]}';
I want to build SQL WHERE clause (needed for filterToolbar search in jqGrid), something like this => "WHERE id LIKE %A% AND i_name LIKE %B% " and etc.
I've done this =>
$d = json_decode($j);
$filterArray = get_object_vars($d); // makes array
foreach($filterArray as $m_arr_name => $m_arr_key){
// here I can't made up my mind how to continue build SQL statement which I've mentioned above
}
Any ideas how to do that , thanks preliminarily :)
The first problem is you will want to pull out the groupOp operator.
Then, you have an object and inside that you have an array of objects, so you may want to look at the results of filterArray as that won't have the value you want.
Then, when you loop through, you will want to do it with an index so you can just pull the values out in order.
You may want to look at this question to see how you can get data out of the array:
json decode in php
And here is another question that may be helpful for you:
How to decode a JSON String with several objects in PHP?
There is an answer with an implementation for the server-side php code here
Correction: I had to unescape double-quotes in the 'filters' parameter to get it working:
$filters = str_replace('\"','"' ,$_POST['filters']);

Categories