How to convert mysqli_fetch_assoc results into json format? - php

i am trying to convert the result of my query into a json format so i can grap it with jquery in another file. I dont get any errors but its not recognised as json.
$patientquery = mysqli_query($connect, "SELECT * FROM login WHERE assignedTo='$logID'");
$numrows = mysqli_num_rows($patientquery);
if($numrows > 0)
{
while($rows = mysqli_fetch_assoc($patientquery))
{
$dbloginID = $rows['loginID'];
$dbname = $rows['name'];
$result[] = array('patient'=>array('id' => $dbloginID, 'name' => $dbname));
}
}
else
{
$result[] = 'No Patients yet';
}
echo json_encode($result);

please try this:
$patientquery = mysqli_query($connect, "SELECT * FROM login WHERE assignedTo='$logID'");
$numrows = mysqli_num_rows($patientquery);
$result = array();
if($numrows > 0)
{
while($rows = mysqli_fetch_assoc($patientquery))
{
$dbloginID = $rows['loginID'];
$dbname = $rows['name'];
$result['patient'][] = array('id' => $dbloginID, 'name' => $dbname);
}
}
else
{
$result[] = 'No Patients yet';
}
echo json_encode($result);

You should declare $result outside while loop like this
$result = array();

Related

PHP - Insert Value with Key from another array into Array in Specific Place

I am trying to create a JSON object as an array from the data received from the SQL Query. Currently the encoded JSON I have got is:
[{"firstname":"Student","lastname":"1"},{"firstname":"Student","lastname":"2"},{"firstname":"Student","lastname":"3"}]
The values I want to insert from another array, the values are in corresponding order to the each array in the JSON above: (JSON)
["85.00000","50.00000","90.00000"]
So the JSON should look like:
{"firstname":"Student","lastname":"1","grade":"85.00000"}
My Current Code:
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
$sqldata = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
foreach($userid as $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
$sqlr = json_encode($sqldata);
$grd = json_encode($grade);
echo $sqlr;
echo $grd;
mysqli_close($conn);
try this code:
foreach($userid as $x => $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row['grade'] = $grade[$x];
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
I added the Variable $x and added $row['grade'] with the same index on the $gradearray
function set_column_values($arr, $column_name, $column_values) {
$ret_arr = array_map(function($arr_value, $col_value) use ($column_name) {
$arr_value[$column_name] = $col_value;
return $arr_value;
}, $arr, $column_values);
return $ret_arr;
}
$sqldata = set_column_values($sqldata, 'grades', $grade);
$sqlr = json_encode($sqldata);
var_dump($sqlr);
Hope it helps!

Why is this piece of code giving me duplicate results?

This is probably really easy and I'm probably gonna kick myself up the arse after this, but I have the following code which displays either html or json of data from a table and returns it.
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
}
?>
Now let's say for example, we want the json result, I'm getting the following string:
[{"id":1,"name":"My Tree","connections":4360}][{"id":1,"name":"My Tree","connections":4360},{"id":4,"name":"Another Tree","connections":0}]
Now for some reason, it's giving me the first result in one array, and then the same result, but with the other rows, in a separate array.
Fixed it, I knew it'd be silly:
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
}
//Moved echo outside of while loop.
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
?>

merging two array into single inside json_encode

I have to combine two array into single inside Json encode. my code is,
$email = $_GET["email"];
$password = $_GET["password"];
$query = "SELECT * FROM tbl_user_login WHERE email='$email' AND password='$password' AND verification='1'";
$result = mysqli_query($c, $query) or die(mysqli_error($c));
$length = mysqli_num_rows($result);
if($length == 1)
{
$var[] = array('status'=>"success");
while($obj = mysqli_fetch_object($result))
{
$var[] = $obj;
}
echo '{"login":'.json_encode($var).'}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"login":['.json_encode($arr).']}';
}
Now the result is,
{"login":[{"status":"success"},{"login_id":"1","name":"Jithin Varghese","password":"some","phone":"","email":"example#gmail.com","addr":"","city":"","state":"","pincode":"0","type":"STD","verification":"1"}]}
And the require output is,
{"login":[{"status":"success","login_id":"1","name":"Jithin Varghese","password":"some","phone":"","email":"example#gmail.com","addr":"","city":"","state":"","pincode":"0","type":"STD","verification":"1"}]}
How to combine array. I have tried a lot.
Change
$var[] = array('status'=>"success");
while($obj = mysqli_fetch_object($result))
{
$var[] = $obj;
}
to
$var['status'] = "success";
// use the assoc fetch here.. to avoid casting to array
while($arr = mysqli_fetch_assoc($result))
{
$var = array_merge($var, $arr);
}
You can use array_merge to get the exact output you request:
$email = $_GET["email"];
$password = $_GET["password"];
$query = "SELECT * FROM tbl_user_login WHERE email='$email' AND password='$password' AND verification='1'";
$result = mysqli_query($c, $query) or die(mysqli_error($c));
$length = mysqli_num_rows($result);
$response = [];
if($length == 1)
{
$response['login'] = arry(array_merge(array('status'=>"success"), mysqli_fetch_assoc($result)));
}
else
{
$response['login'] = array(array('status'=>"notfound"));
}
header('Content-Type: application/json');
echo json_encode($response);
Note that it seems unnecessary to have login property be an array when there is only one result, so it would make sense to remove the outer array wrap:
if($length == 1)
{
$response['login'] = array_merge(array('status'=>"success"), mysqli_fetch_assoc($result));
}
else
{
$response['login'] = array('status'=>"notfound");
}
It's a wild guess, but try this.
$result = array(
'login' => $var
);
echo json_encode($result);

Returning mysqli results outside of function

Given the following code:
function fetchData($mysqli){
$sql = "select * from `test`";
$result = mysqli_query($mysqli,$sql);
return $result;
}
$result = fetchData($mysqli);
while($row = mysqli_fetch_array($result)){
echo $row['id'];
}
My code is obviously more complicated than this. It loops itself until it yields some results changing some variables at each iteration.
$result is empty. What am I doing wrong? Thank you!
FULL CODE:
function fetchItem($itemID, $period, $mysqli){
$periodArray = array('7', '30', '60', '90', '180');
while (current($periodArray) !== $period) next($periodArray);
$currentPeriod = current($periodArray);
$sql = "SELECT * from `test` where `period` = '$period'";
$result = mysqli_query($mysqli,$sql);
$row_count = $result->num_rows;
if($row_count < 5){
$currentPeriod = next($periodArray);
fetchItem($itemID, $currentPeriod, $mysqli);
} else if($row_count >= 5){
$currentPeriod = current($periodArray);
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
// var_dump($rows); <-- returns all results
return $rows;
}
}
$output = fetchItem($itemID, $period, $mysqli);
echo '<pre>';
print_r($output); <-- NULL
echo '</pre>';
As you can see if I don't get results for a given period it moves onto the next one.
Your code should be:
function fetchData($mysqli){
$sql = "select * from `test`";
$init = mysqli_query($mysqli, $sql);
$result = $init->fetch_array(MYSQLI_ASSOC);
return $result;
}
$result = fetchData($mysqli);
foreach($result as $row){
echo $row['id'];
}

PDO: Like condition doesn't work using bindParam

well... why doesn't work this sql statement?
public function searchProfile() {
$termino = $this->term;
$termino = "%".$termino."%";
$sql = "SELECT * FROM cat_perfiles WHERE UPPER(Nombre) LIKE UPPER(:term)";
$result = $this->dbConnect->prepare($sql) or die ($sql);
$result->bindParam(':term',$termino,PDO::PARAM_STR);
$numrows = $result->rowCount();
$jsonSearchProfile = array();
if ($numrows > 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$jsonSearchProfile[] = array(
'IdPerfil' => $row['Id'],
'NomPerfil' => $row['Nombre'],
'DesPerfil' => $row['Descripcion'],
'EdoPerfil' => $row['Activo']
);
}
$jsonSearchProfile['success'] = 'success';
return $jsonSearchProfile;
} else {
return false;
}
}
I check data from $this->term and is correct! But when compare with LIKE doesn't work.
I hope can help me!
You forgot to execute the query
$result->execute();

Categories