Creating token list from mysql query into json - php

i have recently started using the twitter typeahead addon for a new project and have hit a bit of a snag, i am querying 2 columns in 1 table for the data to search, i have it working fine when just searching 1 column however when moving to two i believe i need to start using tokens for the search.
however i cant figure out a way to add in tokens into my array to then encode them to json and return back to the search
this is my code so far:
$dbh = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', '');
$stmt = $dbh->prepare('SELECT NAME, CLID FROM customer');
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['NAME'] = $row['NAME'];
$row_array['CLID'] = $row['CLID'];
$row_array['tokens'] = "";
$results[] = $row_array;
}
$json = json_encode($results);
echo $json;
return $json;
the tokens line is going into the array fine however im not sure on how to format it, i understand it needs to be in the format of
tokens:[
"token1", "token2", "token3"
]
the tokens will be the values of the NAME and CLID, how can i go about creating the tokens to ideally look like this:
{
name: "name",
CLID: "CLID",
tokens: [
"name1", "clid1", "name2", "clid2", "name3", "clid3"...
]
}

Managed to figure it out by reading up some more, to create a nested json element you need to add in through an array within an arry
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['NAME'] = $row['NAME'];
$row_array['CLID'] = $row['CLID'];
$row_array['tokens'] = array($row["NAME"],$row["CLID"]); //create new array and add the tokens you want
$results[] = $row_array;
}

Related

How to write JSON array in key:value format

I am trying to get a JSON array form PHP output which fetches multiple values from the database and converts to JSON array. The PHP code is as follows:
php
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
echo json_encode($response);
It gives the following output:
JSON
{"dblist":["a","arsod"]}
But, in order to extract values from JSON, the needed array is like:
json
{"dblist":{"name":"a","name":"arsod"}}
how can I achieve this? I want to fetch these values in android app.
Try this:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
$dblist = [];
while($row = $result->fetch_assoc()){
$dblist[] = ['name'=>$row['dbname']];
}
$response['dblist'] = $dblist;
echo json_encode($reposne);
I basicaly added [] to $dbList so it looks like $dbList[] = ...
And with this, you will get a valid JSON that looks like this:
{"dblist":[{"name":"a"},{"name":"b"}]}
AS you requested output is not a good idea, since you will have duplicate keys in JSON
Your error is a common mistake and basically only effects this row:
$dblist = array('name'=>$row['dbname']);
where you set $dblist to a new created array in each iteration. What you want to do is adding a new entry to a list on every iteration
$entry = array('name'=>$row['dbname']);
array_push($dblist, $entry);
Which is the same, as
$entry[] = array('name'=>$row['dbname']);

Error while display json from sql database - PHP

I made a script to display data from online SQL database into JSON format.
The problem is, I don't have the format i was looking for, I get 2 [ more while i wanted only one:
A part of my script:
$sql = "select pseudo, dixsec from user;";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
$arrray = array("server_response" => array($rows));
print json_encode($arrray);
What i get (You can see here that i have 2 "["):
Json i get
How can i solve it and get only one "[" ?
$rows is already an array.
Try with: $arrray = array("server_response" => $rows);

fetch_array() - cannot add multiple array fields to new array

I am trying to return a json from a MySQL query to use it with xCode but I cannot get an array of several objects with multiple fields. I have read the documentation on php.net and over here, but I still can't get it.
1) Let's say I have a MySQL table with 3 rows (for example 3 people). Each row contains 3 fields (lastname, firstname, dateOfBirth):
$result = mysqli_query($mysqli, $sql) // where $sql = "SELECT * FROM tbl_syncList"
$resultArray = array();
while ($row = $result->fetch_array()) {
$resultArray[] = $row["lastname"];
}
echo json_encode($resultArray); // --> return "["Lastname1", "Lastname2"...] - that's okay, I understand I return the value of the key "lastname"
I don't know how to get an array with the entire rows (all the fields at once), like:
[["Firstname1", "Lastname1", "dateOfBirth1"], ["Firstname2", "Lastname2", "dateOfBirth2"],...]
I tried to replace
$resultArray[] = $row["lastname"];
with:
$resultArray[] = $row;
but it just gives the world...
"array"
...with no content. Does anyone have an idea?
Thanks a lot!
Are you sure the array is properly populated to begin with? print_r($resultArray) and see what you have there with = $row (which is correct).

PHP Implode returning single entry

I'm trying to use implode() in a script to return the result of an SQL query as a string so I can insert it into another table, however whenever I manage to get the implode to return anything it will only return a single result, even though the query returns more than one result.
Note: my PHP is not the strongest and I am using pre-existing code and reworking it, which is why a lot of the code will look like it's meant for a JSON API.
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Events Scheduled!";
$response["events"] = array();
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["id"];
$post["message"] = $row["message"];
$post["pin"] = $row["pin"];
array_push($response["events"], $post);
$matstring=implode("', '",$post);
}
}
When echo'd out I get:
3', 'Test to check multiple entries are in array for when the check is made, this should be seen.', '12345
imploding $response['events'] returns "Array, Array" and everything else I have tried returns nothing. Where should I look to get the other entry?
I think what are you want is like this:
$str = "'".implode(",'", $post)."'";
echo $str;

How do I fill a PHP array with data from MySQL?

I'm using the Twilio API to send sms. I'm trying to change it so that I can send to a list of recipients from mysql results.
The example code given is:
$people = array(
"+14155551212" => "First Lastname",
);
My code is:
$people = array(
while($res = mysql_fetch_array($usersphone)) {
$people[$res['UserMobile']] = $res['UserFirstName'];
}
);
The syntax is bad but I can't figure out where.
You can't put control structures into arrays.
$people = array();
while ($res = mysql_fetch_array($usersphone)) {
$people[$res["UserMobile"]] = $res["UserFirstName"];
};
Also, there's a ton of posts here on SO that will tell you all about not using the mysql_* functions anymore, since they're deprecated.
You have logic in your array definition. You should define the array, and then populate it with the while.
// define the array
$people = array();
while($res = mysql_fetch_array($usersphone)) {
// populate key with mobile and value with name
$people[$res['UserMobile']] = $res['UserFirstName'];
}

Categories