I am trying to insert data from database into an array, using while loop, here is my database:
id resulst
152556 0
152555 1
152553 1
152552 0
152551 1
152550 0
152549 1
Here is the code that I did:
$output = [
"online" => 0,
"success" => 0,
"servers" => []
];
$mini_result = $db->query("SELECT * FROM `sessions` WHERE status = '1' LIMIT 5");
while( $result = $mini_result->fetch()){
$output['servers']['mini_result'] = [
$result['id'] => $result['result']
];
}
$output["online"] = 1;
$output["success"] = 1;
echo json_encode($output, JSON_PRETTY_PRINT );
Output:
{
online: 1,
success: 1,
servers: {
mini_result: {
152556: "0"
}
}
}
It only prints 1 element, not 5 as I would like. This is the output I want:
{
online: 1,
success: 1,
servers: {
mini_result: {
152556: "0",
152555: "1",
152553: "1",
152552: "0",
152551: "1"
}
}
}
Can you help me?
You overwrite the result on every loop of the loop. What you need to do is:
while($result = $mini_result->fetch()) {
$output['servers']['mini_result'][$result['id']] = $result['result'];
}
This does get quickly quite confusing. You can simplify it, like this:
$miniResult = [];
while($result = $mini_result->fetch()) {
$miniResult[$result['id']] = $result['result'];
}
$output['servers']['mini_result'] = $miniResult;
This what u need:
$mini_result = $db->query("SELECT * FROM `sessions` WHERE status = '1' LIMIT 5");
$output['servers']['mini_result'] = [];
while( $result = $mini_result->fetch()){
$output['servers']['mini_result'][$result['id']] = $result['result'];
}
Related
this is my json response:
{"risultato":"1","ris":[[{"pda":"788","num1":"83","num2":"10","num3":"207410"},{"pda":"232","num1":"83","num2":"14","num3":"204935"}]]}
as you can see there is an extra square bracket, how can I remove it?
the result I would like this:
{"risultato":"1","ris":[{"pda":"788","num1":"83","num2":"10","num3":"207410"},{"pda":"232","num1":"83","num2":"14","num3":"204935"}]}
php:
$stmtcarte = $connection->prepare("SELECT GROUP_CONCAT(concat.pda) as pda, GROUP_CONCAT(concat.num1) as num1,GROUP_CONCAT(concat.num2) as num2, GROUP_CONCAT(concat.num3) as num3 FROM (SELECT pda, num1, num2, num3 FROM giocatori WHERE categoria=? ORDER BY RAND() LIMIT 2 ) concat");
$categoria=$categoriaselezionata;
$stmtcarte->bind_param("s",$categoria);
$stmtcarte->execute();
$risultatocarte = $stmtcarte->get_result();
$numero_giocatori = $risultatocarte->num_rows;
$result=array("risultato"=>"1", "ris"=>"");
while($rispostacarte=$risultatocarte->fetch_assoc()){
$result['ris']=array($rispostacarte);
$ris = $result["ris"][0];
$tempRis = [];
foreach ($ris as $key => $value) {
$explodedArray = explode(",", $value);
$length = count($explodedArray);
for ($i=0; $i < $length ; $i++) {
$tempRis[$i][$key] = $explodedArray[$i];
}
}
$result["ris][0] = $tempRis;
echo json_encode($result);
}
$stmtcarte->close();
You can use simple code like:
<?php
$query = "SELECT pda, num1, num2, num3
FROM giocatori WHERE categoria=?
ORDER BY RAND()
LIMIT 2";
// get DB data using PDO
$stmt = $pdo->prepare($query);
$stmt->execute([$category]);
$risultato = [
'risultato' => 1,
'ris'=>[]
];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$risultato['ris'][] = $row;
}
print_r(json_encode($risultato, JSON_PRETTY_PRINT));
Test PHP & MySQL code here
Result:
{
"risultato": 1,
"ris": [
{
"pda": "788",
"num1": "83",
"num2": "10",
"num3": "207410"
},
{
"pda": "232",
"num1": "83",
"num2": "14",
"num3": "204935"
}
]
}
My database have three tables(category,catgory_details,questions), Now one category have many questions. I want to have a JSON response like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol",
"What is ur name?"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?",
"What is ur name?"
]
}
}
]
but my code is returning only one row from questions tables like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?"
]
}
}
]
Following is my php code:
<?php
header("Content-Type: application/json");
include('db.php');
$result = mysqli_query($conn,"SELECT * FROM categories ORDER BY id ASC");
$json_response = array();
while ($row = mysqli_fetch_array($result))
{
$row_array = array();
$row_array['category'] = $row['category'];
$id = $row['id'];
$detail_query = mysqli_query($conn,"SELECT * FROM category_details WHERE category_id=$id");
$question_query = mysqli_query($conn,"SELECT * FROM questions WHERE category_id=$id");
if($question_query->num_rows !== 0){
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
);
}
}
}
else{
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$myid = $detail_fetch['id'];
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
);
}
}
array_push($json_response, $row_array);
}
echo json_encode($json_response);
?>
What changes should I make in order to get my required JSON response?
Instead of building $row_array['deatils'] within the question_fetch loop, you should do it within the detail_fetch loop, and then populate just the questions sub-array within the question_fetch loop
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => array(),
);
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils']['questions'][] = $question_fetch['question'];
}
}
Try to change :
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
to :
'questions' => $question_fetch['question'],
So you will have the full array of questions included in the response.
I have a query which I want the results inserted in an array so after all I'll encode it into a JSON, but my problem is that I want the data to be set like this:
array[0] = project1, project2, project3;
array[1] = item1, item2, item3;
and I'm having this:
array[0] = project1;
array[1] = project2;
array[2] = project3;
and so on..
this is what I've done so far:
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$proj_name = $proj['proj_name'];
$proj_beg = $proj['proj_beg'];
$proj_end = $proj['proj_end'];
array_push($info, $proj_name, $proj_beg, $proj_end );
}
}
echo json_encode($info);
my query result gave me these result:
["nome", "0000-00-00", "0000-00-00", "Projeto 2", "2016-12-12", "2020-07-30", "Projeto", "2017-02-03", "2018-03-10"]
and this is my $.getJSON code:
$.getJSON("includes/get_area.php",function(data){
console.log(data);
})
What am I doing wrong?
Try this one; this will add a list in each one of the three array indexes.
$info = array();
$items = mysql_query("SELECT * FROM `vision`.`projects` WHERE proj_area = 'area_1'");
if (mysql_num_rows($items) != 0) {
while($proj = mysql_fetch_array($items)) {
$info[0][] = $proj['proj_name'];
$info[1][] = $proj['proj_beg'];
$info[2][] = $proj['proj_end'];
}
}
echo json_encode($info);
I have a mysql table (name:"messages") that has three columns as below:
messageID, fromUserID, content
I wish to have a json output using php script like following format; I need to seprate messages of each user (fromUserID column).
JSONOutput:
{
"newCount":"x",
"messages":
[
{
"fromUserID":"x",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"y",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"z",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
}
]
}
My PHP Script:
$query = mysqli_query($con,"SELECT * FROM messages ORDER BY fromUserID");
$outputArray = array();
$outputArray['hasNew'] = mysqli_num_rows($query);
$messagesArray = array();
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray['MessagesArray'][] = $MSGArray;
}
$outputArray['Messages'][] = $messagesArray;
}
echo json_encode($outputArray);
But with above script I give a wrong result as below:
{
"hasNew":6,
"Messages":
[
{
"fromUserID":"24",
"MessagesArray":
[
{"messageID":"4","content":"test"},
{"messageID":"3","content":"test"},
{"messageID":"6","content":"test"},
{"messageID":"5","content":"test"},
{"messageID":"1","content":"test"},
{"messageID":"2","content":"test"}
]
}
]
}
My PHP Script just using last fromUserID value to grouping messages !!!
Please let me know where I'm wrong ...
Try it
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray[$row['fromUserID']]['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray[$row['fromUserID']]['MessagesArray'][] = $MSGArray;
}
foreach($messagesArray as $value) {
$outputArray['Messages'][] = $value;
}
}
$query = "SELECT `contact_id`, `user_id`, `date_backup`, `first_name`, `last_name` FROM tbl_contacts WHERE date(`date_backup`) = (SELECT MAX(date(`date_backup`)) FROM tbl_contacts WHERE `user_id`= '$userId' ) ORDER BY `date_backup` DESC, `contact_id` ASC";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
$contacts = array(array());
$contactId = $row['contact_id'];
$names["first_name"] = $row['first_name'];
$names["last_name"] = $row['last_name'];
$contacts["names"][] = $names;
// Phone
$phoneQuery = "SELECT * FROM tbl_phone_details WHERE contact_id = '$contactId' AND date(`date_backup`) = (SELECT MAX(date(`date_backup`)) FROM tbl_phone_details WHERE `contact_id`= '$contactId')";
$phoneResult = mysql_query($phoneQuery);
$total = mysql_affected_rows();
if($total >= '1') {
while($phoneRow = mysql_fetch_assoc($phoneResult)) {
$phones["phone_number"] = $phoneRow['phone_number'];
$phones["phone_type"] = $phoneRow['phone_type'];
$contacts["phones"][] = $phones;
}
} else {
$contacts["phones"][] = array();
}
// Email
$emailQuery = "SELECT * FROM `tbl_email_details` WHERE `contact_id` = '$contactId' AND date(`date_backup`) = (SELECT MAX(date(`date_backup`)) FROM tbl_email_details WHERE `contact_id`= '$contactId')";
$emailResult = mysql_query($emailQuery);
$total = mysql_affected_rows();
if($total >= '1') {
while($emailRow = mysql_fetch_assoc($emailResult)) {
$emails["email_address"] = $emailRow['email_address'];
$emails["email_type"] = $emailRow['email_type'];
$contacts["emails"][] = $emails;
}
} else {
$contacts["emails"][] = array();
}
// Address
$addressQuery = "SELECT * FROM `tbl_address_detail` WHERE `contact_id` = '$contactId' AND date(`date_backup`) = (SELECT MAX(date(`date_backup`)) FROM tbl_address_detail WHERE `contact_id`= '$contactId')";
$addressResult = mysql_query($addressQuery);
$total = mysql_affected_rows();
if($total >= '1') {
while($addressRow = mysql_fetch_assoc($addressResult)) {
$address["street"] = $addressRow['street'];
$address["city"] = $addressRow['city'];
$address["state"] = $addressRow['state'];
$address["zip"] = $addressRow['zip'];
$address["country"] = $addressRow['country'];
$address["addressType"] = $addressRow['addressType'];
$contacts["address"][] = $address;
}
} else {
$contacts["address"][] = array();
}
$contectInfoJson["contacts"][] = $contacts;
}
$allContactJson["AllContacts"] = $contectInfoJson;
header('Content-Type: application/json');
echo json_encode($allContactJson);
OUTPUT OF CODE :-
AllContacts: {
userId: "15",
contacts: [
{
0: [ ], // Not needed
names: [ // Instead of array i need simple object of names
{
first_name: "ABC",
last_name: "XYZ"
}
],
phones: [
{
phone_number: "+911234567890",
phone_type: "Work"
},
{
phone_number: "+919876543210",
phone_type: "Home"
}
],
emails: [
[ ] //This is also extra and not needed.
],
address: [
{
street: "India",
city: "",
state: "",
zip: "",
country: "",
addressType: ""
}
]
},
REQUIRED OUTPUT:-
AllContacts: {
userId: "15",
contacts: [
{
names:
{
first_name: "ABC",
last_name: "XYZ"
},
phones: [
{
phone_number: "+911234567890",
phone_type: "Work"
},
{
phone_number: "+919876543210",
phone_type: "Home"
}
],
emails: [],
address: [
{
street: "India",
city: "",
state: "",
zip: "",
country: "",
addressType: ""
}
]
},
I am facing 2-3 small problem in the code.
First is that i am getting 0 : [] on every start of the object.
2nd one is names is array and i want it to be object not array.
3rd is emails :[ [] ], i want blank array if data is not available, but i am getting array inside array. I just want emails :[].
Replace $contacts = array(array()); with $contacts = array();. Should remove 0 : [].
$contacts["emails"][] = array(); is triggered probably, so try to replace it with $contacts["emails"] = array();
Replace $contacts["names"][] = $names; with $contacts["names"] = $names;