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

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.

Related

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.

Load Json Data into an AmChart

I beginner to Amchart and am test load data in Amchart using php
this is my format json
[{"date":"2018-01-01","column-1":"5187"},{"date":"2018-01-02","column-1":"15790"},{"date":"2018-01-03","column-1":"15826"},{"date":"2018-01-04","column-1":"17026"},{"date":"2018-01-05","column-1":"17908"},{"date":"2018-01-01","column-2":"2143"},{"date":"2018-01-02","column-2":"6192"},{"date":"2018-01-03","column-2":"6106"},{"date":"2018-01-04","column-2":"6532"},{"date":"2018-01-05","column-2":"7000"}]
and this is my code
var data1 = <?php
include('connect.php');
$data = array();
$arr = array();
$query = "SELECT * FROM shell_table_graph";
$db = mysql_query($query);
while($rows = mysql_fetch_assoc($db)) {
$data[] = ['column' => $rows['column'], 'formula' => $rows['calculation']];
}
foreach($data as $rowss) {
$formula = $rowss['formula'];
$query = "SELECT Date, SUM(".$formula.") AS Formula FROM eod_split_interval WHERE Date BETWEEN '2018-01-01' AND '2018-01-05' GROUP BY Date";
$db = mysql_query($query);
while($r = mysql_fetch_assoc($db)) {
$arr[] = ['date' => $r['Date'], $rowss['column'] => $r['Formula']];
$code = json_encode($arr);
}
}
echo $code;
?>;

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

php mysql_fetch_assoc to json encode

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

Add new array key inside function

I have an array that is populated by a mysql_fetch_assoc. After the array is populated by the columns I want from the database, I would like to add another key to the array, using values that I obtain earlier in the function. I tried to accomplish this with a foreach loop, but my function is not returning the array. Where have I gone wrong?
//calculates payout
function calculate_payout($id){
$result = mysql_query("SELECT `result` FROM `bets` WHERE `id` = {$id}");
echo mysql_error();
$wager_total = mysql_query("SELECT SUM(`wager_amount`) AS `wager_total` FROM `wagers` WHERE `id` = '{$id}'");
$correct_wager_total = mysql_query("SELECT SUM(`wager_amount`) AS `correct_wager_total` FROM `wagers` WHERE `id` = '{$id}' AND `wager_option` = '{$result}'");
echo mysql_error();
$incorrect_wager_total = $wager_total - $correct_wager_total;
$sql = " SELECT * FROM `wagers` WHERE `id` = '{$id}' AND `wager_option` = '{$result}'";
echo mysql_error();
$data = mysql_query($sql);
$rows = array();
while(($row = mysql_fetch_assoc($data)) !== false){
$rows[] = array(
'bet_id' => $row['bet_id'],
'id' => $row['id'],
'wager_amount' => $row['wager_amount']
);
}
foreach ($rows as $p_row){
$payout = $p_row['wager_amount'] / $incorrect_wager_total;
$payout = $p_row['wager_amount'] + $payout;
$p_row['payout'] = $payout;
}
return $p_row;
}
The problem is that $p_row is a copy of the row in the array, so modifying it in the loop doesn't have any effect on the original array.
You can fix this by using a reference in the foreach:
foreach ($rows as &$p_row)
Or you can just do this as you're creating the $rows array in the while loop:
while ($row = mysql_fetch_assoc($data)) {
$new_row = array(
'bet_id' => $row['id'],
'id' => $row['id'],
'wager_amount' => $row['wager_amount'],
'payout' => $row['wager_amount'] / $incorrect_wager_total + $row['wager_amount']
);
Also, your return statement is wrong, it should be return $rows; to return the whole array; return $p_row will just return the last row of the array.

Categories