php mysql_fetch_assoc to json encode - php

I am Using Following code php array to encode Json
$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";
$result = mysql_query($query) or die('Errant query: ' . $query);
$numResults = mysql_num_rows($result);
if ($numResults > 0)
{
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data = $row;
}
echo json_encode($data);
}
IT gives Me result like
{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}
But I wanted To result like
{"SignIn":[{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}],"errors":[],"totalNumberOfRecords":1,"responseCode":"00000"}
How Can I do That
Or Suggest Me any other Method to do that

You need to do something like below to get the desired output.
$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";
$result = mysql_query($query) or die('Errant query: ' . $query);
$numResults = mysql_num_rows($result);
if ($numResults > 0)
{
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
$result = ['SignIn' => $data, 'totalNumberOfRecords' => $numResults, 'errors' => [], 'responseCode' => 0000];
echo json_encode($result);
exit;
}

You have to store all information in a array to get what you want.
For example,
$data = array("id" =>"26","fname"=>"Shankar","lname"=>"Salunkhe","category_name"=>"2");
$array = array("SignIn" => $data, "errors" => [], "totalNumberOfRecords" => 1,"responseCode" => "00000");
$result = json_encode($array);

Related

How can i get all of my users from sql datebase with using php [duplicate]

This question already has answers here:
mysqli_fetch_array returning only one result
(3 answers)
Closed 3 years ago.
In $result should be all of users from datebase, but it takes only first person and shows error.
My php code:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once 'connect.php';
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = array();
$result['osoby'] = array();
$row = mysqli_fetch_assoc($response);
$index['name'] = $row['imie'];
$index['surname'] = $row['nazwisko'];
array_push($result['osoby'], $index);
$result['success'] = "1";
echo json_encode($result);
}
Its giving you 1 record because you are only printing 1 record,
Using $row = mysqli_fetch_assoc($response); will always give you last row if you not use loop here.
You need to use while loop to get all rows like:
<?php
$i = 0;
$result = array(); // initialize
while($row = mysqli_fetch_assoc($response)){
$result[$i]['name'] = $row['imie'];
$result[$i]['surname'] = $row['nazwisko']; // store in an array
$i++;
}
$finalResult['osoby'] = $result; // storing as you need
$finalResult['success'] = "1"; // no idea about this but adding this also
echo json_encode($finalResult); // encode with json
?>
You can loop the result-set and append an array of your values to the $result array.
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = ['osoby' => []];
while ($row = mysqli_fetch_assoc($response)) {
$result['osoby'][] = ['name' => $row['imie'], 'surname' => $row['nazwisko']];
}
$result['success'] = "1";
echo json_encode($result);
If you have the mysqlnd driver installed, you can also use mysqli_result::fetch_all() method
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = ['osoby' => mysqli_fetch_all($response, MYSQLI_ASSOC)];
$result['success'] = "1";
echo json_encode($result);
You have to loop the result array.
$resultJson = array();
$resultJson['osoby']=array()
$query = "SELECT imie,nazwisko FROM users";
$result = $mysql->query( $query );
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
// fetch information out of the $row..
$resultJson['osoby'][] = ['name' => $row['imie'], 'surname' => $row['nazwisko']];
}
}
print json_encode($resultJson);

Can't retrieve information from MySQL response on PHP

I'm able to get the response from MySQL server, but I can't seem to put it in a variable
$filmNameList2 = [];
require('connect.php');
$query = "SELECT `title`,`year` FROM `filmList` WHERE year=' (2019)'";
$result = mysqli_query($connect, $query) or die(mysqli_error($connect));
$json_array = array();
while($row=mysqli_fetch_array($result))
{
$json_array[] = $row;
// print_r($row); outputs Array ( [0] => Abruptio [title] => Abruptio [1] => (2019) [year] => (2019) )
}
$filmNameList2[] = $json_array->array[0]->array[0]->title;
// I have tried json_array->array[0]->title; json_array->title;
print_r($filmNameList2);
result that I get :
Array ( [0] => )
$filmNameList2 = array();
require('connect.php');
$query = "SELECT `title`,`year` FROM `filmList` WHERE year=' (2019)'";
$result = mysqli_query($connect, $query) or die(mysqli_error($connect));
while($row=mysqli_fetch_array($result))
{
$object = array(
'title' => $row[0],
'year' => $row[1]
);
array_push($filmNameList2 , $object );
}
echo json_encode($filmNameList2);
print_r($filmNameList2);
try this code...
$query = "SELECT `title`,`year` FROM `filmList` WHERE year=' (2019)'";
$result = mysqli_query($connect, $query) or die(mysqli_error($connect));
$json_array = array();
while($row=mysqli_fetch_object($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
print_r($json_array);
$filmNameList2[] = $json_array[0]['title'];
Access the first row, then the title element in it.

Fetch data from database using json without using an array

I would like to retrieve objects from the database in JSON using PHP and MySql. I would just like to know how to do this without having to create an array? Can it be done?
If so, can I get an example of how that can be done with this draft piece of code?
$sql = "SELECT Email , FirstName, LastName,Contact FROM tblUser where UserID=sessionID";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array ($result)) {
$arr = array(
$row["Email"],
$row["FirstName"],
$row["LastName"],
$row["Contact"]
);
array_push($json, $arr);
}
$jsonstring = json_encode($json);
echo $jsonstring;
$sql = "select name,email from contact";
$res = mysqli_query($conn,$sql) or die(mysqli_error($conn));
$num = mysqli_num_rows($res);
$json = array();
if($num > 0)
{
while ($obj=mysqli_fetch_object($res))
{
$json[] = $obj;
}
}
echo json_encode($json);
output:
[{"name":"test","email":"test#gmail.cmom"},{"name":"test1","email":"test1#gmail.cmom"}]

Creating php json object array inside of array

I'm having trouble trying to figure out how would I create a Php json object that has an array inside of array. I have been working on this for hours and can't figure it out. Should I use oject inside my while loop and add array?
I Would like to have my answer array inside my question array like this.
{
"success":true,
"total":2,
"question":[
{
"id":"1",
"product":"The Product",
"question":"Some question here"
"answer":[
{
"answer_id":"1",
"answer":"First answer",
"is_correct":"1",
"question_id":"1"
},
{
"answer_id":"2",
"answer":"Second answer",
"is_correct":"1",
"question_id":"1"
}
]
}
],
"question":[
{
"id":"2",
"product":"The Product",
"question":"Some question here"
"answer":[
{
"answer_id":"1",
"answer":"First answer",
"is_correct":"0",
"question_id":"1"
},
{
"answer_id":"2",
"answer":"Second answer",
"is_correct":"1",
"question_id":"1"
}
]
}
],
See code below.
$question_arr = array();
$answer_arr = array();
//Question table results
$sql = "SELECT * FROM Questions WHERE product='".$product."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row_question_array['id'] = $row['ID'];
$row_question_array['product'] = $row['product'];
$row_question_array['question'] = $row['question'];
array_push($question_arr,$row_question_array);
//Anwser table results
$sql2 = "SELECT * FROM Answers WHERE question_id='".$row['ID']."'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$row_anwser_array['answer_id'] = $row2['answer_id'];
$row_anwser_array['product'] = $row2['product'];
$row_anwser_array['answer'] = $row2['answer'];
$row_anwser_array['is_correct'] = $row2['is_correct'];
$row_anwser_array['question_id'] = $row2['question_id'];
array_push($answer_arr,$row_anwser_array);
}
}
} else {
echo "question 0 results";
}
$myObj->success = true;
$myObj->total = $result->num_rows;
$myObj->question = $question_arr;
$myObj->answer = $answer_arr;
//echo json_encode($question_arr);
//echo json_encode($answer_arr);
echo json_encode($myObj);
There's no need to create two separate $question_arr or $answer_arr arrays. Instead, just create one empty result array $resultArr and refactor your code in the following way,
$resultArr = array();
$sql = "SELECT * FROM Questions WHERE product='".$product."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultArr = array('success' => true, 'total' => $result->num_rows);
while($row = $result->fetch_assoc()) {
$resultArr['question'][$row['ID']] = array('id' => $row['ID'], 'product' => $row['product'], 'question' => $row['question']);
//Anwser table results
$sql2 = "SELECT * FROM Answers WHERE question_id='".$row['ID']."'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$resultArr['question'][$row['ID']]['answer'][] = $row2;
}
}
$resultArr['question'] = array_values($resultArr['question']);
} else {
$resultArr = array('success' => false, 'total' => 0);
echo "question 0 results";
}
echo json_encode($resultArr);

Creating an associative array in PHP from sql results, for json

I'm trying to create an associative array from sql results for json_encode.
here's my code:
$timelineQuery = "SELECT * FROM timeline_table";
$contentQuery = "SELECT * FROM content_table";
$picQuery = "SELECT * FROM pic_table";
$sql = mysql_query($timelineQuery) or die(mysql_error());
$sql2 = mysql_query($contentQuery) or die(mysql_error());
$sql3 = mysql_query($picQuery) or die(mysql_error());
$mainArray = array(
'timeline' => $timelineArray = array(
'content' => $contentArray = array(
'pictures' => $picArray = array(),
),
),
);
while($row = mysql_fetch_assoc($sql)) {
$timelineArray[] = $row;
}
while($row2 = mysql_fetch_assoc($sql2)) {
$contentArray[] = $row2;
}
while($row3 = mysql_fetch_assoc($sql3)) {
$picArray[] = $row3;
}
echo stripslashes(json_encode($mainArray));
If I json_encode my $mainArray as it is, the returned json has the syntax I'm looking for, but I've not been able to fill the array without adding it to the end of my array.
{"timeline":{"content":{"pictures":[]}}}
first:
while($row = mysql_fetch_assoc($sql)) {
$timelineArray[] = $row;
}
while($row2 = mysql_fetch_assoc($sql2)) {
$contentArray[] = $row2;
}
while($row3 = mysql_fetch_assoc($sql3)) {
$picArray[] = $row3;
}
then:
$mainArray = array(
'timeline' => $timelineArray = array(
'content' => $contentArray = array(
'pictures' => $picArray = array(),
),
),
);
echo stripslashes(json_encode($mainArray));
you defined your array with empty arrays and didn't renew it's states.

Categories