Return JSON with id in front - php

How do I pull out the id in front of each JSON return object from my API?
Current:
{
"1516":{
"id":"1516",
"firstname":"Aluno",
"lastname":"Teste",
"email":"teste#gmail.com",
"dlastaccess":"28-10-2016",
"coursename":"Curso Demonstra\u00e7\u00e3o"
}
}
How do I want to leave:
[
{
"id":"1516",
"firstname":"Aluno",
"lastname":"Teste",
"email":"teste#gmail.com",
"dlastaccess":"28-10-2016",
"coursename":"Curso Demonstra\u00e7\u00e3o"
}
]
I'm trying to do this because my checklist-model does not work the way the JSON return comes, so I can not check all the checkboxes.
API:

This does the job:
$json = '{"1516":{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"teste#gmail.com","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}}';
$values = json_decode($json, true);
$values = array_values($values);
echo json_encode($values);
returns:
[{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"teste#gmail.com","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}]

I guess your $result is an array (or object) of this type:
$result[id] = array(sql retrieved);
Because sql returns you a list of results, even if the result is unique. Imagine that your query returned two results, how could you separate them?
Try:
echo json_encode($result[$cursoid])
or
echo json_encode($result->$cursoid)

$cursoid = $_GET['idcurso'];
$sql = 'SELECT
user2.id AS ID,
user2.firstname AS Firstname,
user2.lastname AS Lastname,
user2.email AS Email,
IF (user2.lastaccess = 0,"nunca",
DATE_FORMAT(FROM_UNIXTIME(user2.1astaccess),"%d-96m-W")) AS dLastAccess ,c.fullname AS Coursename
FROM mdl_user_enrolments AS ue
JOIN mdl_enrol AS e ON e.id = ue.enrolid
JOIN mdl_course AS c ON c.id = e.courseid
JOIN mdl_user AS user2 ON user2 .id = ue.userid
WHERE (SELECT timeaccess FROM mdl_user_lastaccess WHERE userid=user2.id AND courseid=c.id) IS NULL and c.id = ?';
$params = array($cursoid);
$result = $DB->get_records_sql($sql, $params);
echo json_encode(array_values($result)); // You can easily access array values without their keys by array_values(array $param) function

Use array_values, default php function
$values = $DB->get_records_sql( $sql, $params );
$result = array_values( $values );
return json_encode($result);

Related

Mysql/PHP Json nested array

I got issue with nested array which seems are not Json object for some reason. When i try for e.g access jsonData["user"] it works, but when i try go deeper such as jsonData["user"]["photo_url"] then it's treated like a string and i cant access the value.
Current code:
<?php
require_once("db_connection.php");
$userId = $_GET["user_id"];
$query = "WITH user AS (SELECT id, JSON_OBJECT('display_name', u.display_name, 'photo_url', u.photo_url) AS user FROM users u WHERE id = :userId), info AS (SELECT id, JSON_ARRAYAGG(JSON_OBJECT('text', text, 'start_at', start_at, 'end_at', end_at, 'status', status)) AS information FROM report GROUP BY id), img AS (SELECT report_id, JSON_ARRAYAGG(JSON_OBJECT('name', name)) AS images FROM report_images GROUP BY report_id), cmt AS (SELECT report_id, COUNT(*) AS totalcomments FROM report_comments rc JOIN users u ON rc.user_id = u.id GROUP BY report_id) SELECT u.user, info.information, img.images, cmt.totalcomments FROM report r JOIN user u ON u.id = r.user_id LEFT JOIN info ON info.id = r.id LEFT JOIN img ON img.report_id = r.id LEFT JOIN cmt ON cmt.report_id = r.id";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Old code which worked:
<?php
require_once("db_connection.php");
require_once("functions.php");
$userId = $_GET["user_id"];
$query = "SELECT * FROM report WHERE `user_id` = :userId";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
foreach ($result as $key => $value) {
$result[$key]["user"] = getUserById($db, $value["user_id"]);
}
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Because you are aggregating some of the values as JSON in your query, you need to decode those first before attempting to use the values and then JSON encode the whole result set. You need to do that as you fetch the data, so replace:
$result = $stmt->fetchAll();
with:
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['user'] = json_decode($row['user']);
$row['images'] = json_decode($row['images']);
$row['comments'] = json_decode($row['comments']);
$result[] = $row;
}

PHP allow special characters from MySQL query column in Array

Creating an array (which I want to encode to JSON) from a MySql select query, but one of the query columns has free text entered by users. I don't want special characters (or 'n/' formatting) in this column preventing the array from populating correctly. Not all rows are being displayed by the current statement and 'n/' etc characters are being included:
echo json_encode($data); //not sure this is in the right part of my code
I've used the below code successfully before but not in an array:
echo nl2br($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8");
My PHP code:
if(!empty($_POST['msg']))
{
$userid = session_id();
$searchStr = get_post($con,'msg');
$aKeyword = explode(" ", $searchStr);
$aKeyword = array_filter($aKeyword); // Remove empty values
$stmt = $con->prepare(
'SELECT
a.ID, a.MessageText, a.cntLikes, IFNULL(b.Type,0) as Type
FROM
(
SELECT m.ID, m.MessageText,count(l.Id) as cntLikes
FROM MessageMain m
LEFT OUTER JOIN Likes l on m.ID = l.PostID
WHERE MessageText REGEXP ?
GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc
)a
LEFT OUTER JOIN
(
SELECT postId, COUNT(*) as type
FROM likes
WHERE userid = ?
GROUP BY postId
)b
on a.Id = b.PostId'
);
$regexString = implode('|', $aKeyword);
$stmt->bind_param('ss',$regexString, $userId);
$stmt->execute();
$result = $stmt->get_result();
$data = array();
if(mysqli_num_rows($result) > 0) {
While($row = $result->fetch_assoc()) {
$data = $row;
echo json_encode($data);
}
}
}
What solved the issue was amending:
$data = $row;
to:
$data[] = array ( 'ID' => $row['ID'], 'UserID' => $row['UserID'], 'MessageText' => nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8") ), 'cntLikes' => $row['cntLikes'], 'Type' => $row['Type'] );
The database column that was stopping the array from pulling back was 'MessageText'. This column had originally come from an Excel spreadsheet where the data was very dirty.
Using
nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8"))
resolved the issue.

Get all the values from single column in MySQL PDO [duplicate]

This question already has answers here:
PDO fetch one column from table into 1-dimensional array
(2 answers)
Closed 5 years ago.
I have value in user_id column (1,47,6). How to get all the values?
I have used following code.
$array_data = array($project_id);
$query = "SELECT * FROM p
INNER JOIN pl ON p.pl_id = pl.pl_id
INNER JOIN user ON p.user_id = user.user_id WHERE
p.p_id=?";
$stmt = $conn->prepare($query);
$stmt->execute($array_data);
$result_data = $stmt->fetchAll( PDO::FETCH_ASSOC );
$ids = array();
foreach($result_data as $rows) {
$ids[] = $rows['user_id'];
}
$id = implode(',',$ids);
echo $id;
This $id returns only the first value (1). I need all 3 values. Please help & thanks in advance.
Declare the $ids array before the loop and echo the imploded content after the array
$array_data = array($project_id);
$query = "select `user_id` from p
inner join pl on p.pl_id = pl.pl_id
inner join user on p.user_id = user.user_id where
p.p_id=?";
$stmt = $conn->prepare($query);
$stmt->execute($array_data);
$result_data = $stmt->fetchAll( PDO::FETCH_ASSOC );
$ids = array(); /* declare variable before loop */
foreach($result_data as $rows) {
$ids[] = $rows['user_id'];
}
$id = implode(',',$ids); /* output after loop */

Get query result as array in codeigniter

I have a query, how do I get the result as an array?
function get_all_transaksi_proses() {
$rs = $this->db->query("SELECT a.id_transaksi,
a.nama,
a.tgl_transaksi,
(SELECT COUNT( id_transaksi ) AS jum
FROM tbl_detail_trs_menu
WHERE id_transaksi = a.id_transaksi) AS jumlah,
a.status_transaksi,
a.total,
b.status_pelanggan,
c.nama_karyawan
FROM tbl_transaksi a
LEFT JOIN tbl_pelanggan b
ON a.id_pelanggan = b.id_pelanggan
LEFT JOIN tbl_karyawan c
ON a.id_karyawan = c.id_karyawan
WHERE a.status_transaksi = 'PROSES' ");
echo json_encode(array("result" => $rs));
}
Like this:
$rs = $this->db->query(...);
$array = $rs->result_array();
https://www.codeigniter.com/user_guide/database/results.html
To get a result in array you have to do this CI 2.2.2:
return $query->result_array();
$query = $this->db->query("select....");
return $query->result(); // it will result an array
or
echo json_encode($query->result()); // this will also result array but direct to json_encode
....hope i help you!

PHP: Join two separate mysql queries into the same json data object

I'm trying to mesh the below mysql query results into a single json object, but not quite sure how to do it properly.
$id = $_POST['id'];
$sql = "SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = '$id'
ORDER BY contracts.end_date";
$sql2 = "SELECT types_id
FROM contracts_types
WHERE contracts_id = '$id'";
//return data
$sql_result = mysql_query($sql,$connection) or die ("Fail.");
$arr = array();
while($obj = mysql_fetch_object($sql_result)) { $arr[] = $obj; }
echo json_encode($arr); //return json
//plus the selected options
$sql_result2 = mysql_query($sql2,$connection) or die ("Fail.");
$arr2 = array();
while($obj2 = mysql_fetch_object($sql_result2)) { $arr2[] = $obj2; }
echo json_encode($arr2); //return json
Here's the current result:
[{"po_number":"test","start_date":"1261116000","end_date":"1262239200","description":"test","taa_required":"0","account_overdue":"1","jobs_id":null,"job_number":null,"companies_id":"4","companies_name":"Primacore Inc."}][{"types_id":"37"},{"types_id":"4"}]
Notice how the last section [{"types_id":"37"},{"types_id":"4"}] is placed into a separate chunk under root. I'm wanting it to be nested inside the first branch under a name like, "types".
I think my question has more to do with Php array manipulation, but I'm not the best with that.
Thank you for any guidance.
Combine the results into another structure before outputting as JSON. Use array_values to convert the type IDs into an array of type IDs. Also, fix that SQL injection vulnerability. Using PDO, and assuming the error mode is set to PDO::ERRMODE_EXCEPTION:
$id = $_POST['id'];
try {
$contractQuery = $db->prepare("SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = ?
ORDER BY contracts.end_date");
$typesQuery = $db->prepare("SELECT types_id
FROM contracts_types
WHERE contracts_id = ?");
$contractQuery->execute(array($id));
$typesQuery->execute(array($id));
$result = array();
$result['contracts'] = $contractQuery->fetchAll(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
echo json_encode($result); //return json
} catch (PDOException $exc) {
...
}
If $contractQuery returns at most one row, change the fetch lines to:
$result = $contractQuery->fetch(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
It would seem like you'd be better served by consolidating the two queries with a JOIN at the SQL level. However, assuming the two arrays have equal length:
for ($x = 0, $c = count($arr); $x < $c; $x++) {
if (isset($arr2[$x])) {
$arr[$x] += $arr2[$x];
}
}
echo json_encode($arr);
Edit: you would need to change from mysql_fetch_object to mysql_fetch_assoc for this to work properly.
Why are you using 2 distinct arrays ? I would simply add the rows of the 2nd query in $arr instead of $arr2. This way, you end up with a single array containing all rows from the 2 queries.

Categories