merging two array into single inside json_encode - php

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);

Related

How to format a json response in php

I am new to php and am trying to return a json response in a particular structure. Here is what I have tried so far:
$response = array();
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branchId'] = $row['branchId'];
$response[$x]['branch'] = $row['branch'];
$response[$x]['customerGroupId'] = $row['customerGroupId'];
$response[$x]['customerGroup'] = $row['customerGroup'];
$response[$x]['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}
The code above returns this response:
However, instead of returning for example "branchId" and "branch" as individual properties, I want to pass their values inside a branchObject such that branch.id == "branchId" and branch.name == "branch".I mean, How may I return the response in the following structure:
And Here is how my database looks like:
How can I achieve this?
You ask for stuff that we are unsure if db result returns but as nice_dev pointed out, you need something like this:
$response = [];
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branch']['id'] = $row['branchId'];
$response[$x]['branch']['name'] = $row['branch'];
$response[$x]['customerGroup']['id'] = $row['customerGroupId'];
$response[$x]['customerGroup']['name'] = $row['customerGroup'];
$response[$x]['customerGroup']['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}

JSON encoding not working

Here is my code to encode data in JSON format, but it doesn't work. The result is []. Where is my mistake?
<?php
$conn = new mysqli('localhost','root','','project');
$data =array();
if(!empty($_GET['masp'])){
$masp =$_GET['masp'];
$sql ="SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)){
$r['masp'] =$data['masp'];
$r['loai'] =$data['loai'];
$r['hangsx']=$data['hangsx'];
$r['tensp']=$data['tensp'];
$r['img']=$data['img'];
$r['gia']=$data['gia'];
$r['nx']=$data['nx'];
}
}
}
print json_encode($data);
?>
You are setting your variables wrong.
In every while cycle you get a new $r variable that you want to add to your $data variable.
$conn = new mysqli('localhost', 'root', '', 'project');
$data = array();
if (!empty($_GET['masp'])) {
$masp = $_GET['masp'];
$sql = "SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn, $sql);
$i = 0;
if ($result) {
while ($r = mysqli_fetch_assoc($result)) {
$data[$i]['masp'] = $r['masp'];
$data[$i]['loai'] = $r['loai'];
$data[$i]['hangsx'] = $r['hangsx']];
$data[$i]['tensp'] = $r['tensp'];
$data[$i]['img'] = $r['img'];
$data[$i]['gia'] = $r['gia'];
$data[$i]['nx'] = $r['nx'];
$i += 1;
}
}
}
print json_encode($data);
You make mistake. You should swap variable data with r inner loop, but probably than also will works unpropely. write in while loop $data [] = $r;

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'];
}

I want to return two results from one function in php

Here is my function in DB_Functions.php, i want to get two different values from two different tables in single function only here is the code what i have tried so far but the values are coming null.
public function getUserMetvalue($exname,$fname) {
$result = mysql_query("SELECT metvalue FROM fitnessactivitylist WHERE activityname='$exname'") or die(mysql_error());
$result1 = mysql_query("SELECT weight FROM users WHERE name='$fname'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
$no_of_rowss = mysql_num_rows($result1);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
if ($no_of_rowss > 0) {
$result1 = mysql_fetch_array($result1);
return $result1;
}
return $result;
} else {
//exercise name not found
return false;
}
}
here is my index.php
//TAG METVALUE
if ($tag == 'metvalue') {
$exname = $_POST['exname'];
$fname = $_POST['fname'];
$usermetvalue = $db->getUserMetvalue($exname,$fname);
if ($usermetvalue != false) {
$response["success"] = 1;
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
echo json_encode($response);
}
else {
$response["error"] = 1;
$response["error_msg"] = "No exercise found!";
echo json_encode($response);
}
}
Spot the differences:
$result = mysql_query("SELECT metvalue etc...
^^^^^^^^
$result1 = mysql_query("SELECT weight etc...
^^^^^^
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
^^^^^^
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
^^^^^
You fetch fields which aren't used later, then attempt to access fields which weren't fetched in the first place...
function a_function() {
$a = 'Learn';
$b = 'Programming.';
return array($a, $b);
}
list($one, $two) = a_function();
echo $one . ' ' . $two;

How to convert mysqli_fetch_assoc results into json format?

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();

Categories