Nesting JSON in PHP - php

I have this in php
$comment = array;
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){
$comment[$row['name']] = $row['comment'];
}
echo json_encode($comment);
Having these results
{"John":"Yo","Dan":"Hello","May":"Bye"}
The problem is I actually have two comments(Zup,Yo) for John, but as you can see, it only displays the last comment of John which is "Yo". So I wanted the results of John to be
{"John":["Yo","Sup"]}
^ is this possible?
How can I do that? Im sorry still having a hard time dealing with JSON. Thanks
This is actually my full code
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){
$comment[$row['name']] = $row['comment'];
$sql_dup = "SELECT name, COUNT(name) AS dup_count
FROM comment
GROUP BY name
HAVING (COUNT(name) > 1)
";
$sqlExec_dup = mysql_query($sql_dup, $connection);
$row_dup = mysql_fetch_array($sqlExec_dup, MYSQL_ASSOC);
if($row['name'] = $row_dup['name']){
$sql_dup2 = "SELECT * FROM comment WHERE name = '{$row['name']}'";
$sqlExec_dup2 = mysql_query($sql_dup2, $connection);
while($row_dup2 = mysql_fetch_array($sqlExec_dup2, MYSQL_ASSOC)){
$x += 1;
if($x <= $row_dup['dup_count']){
$comment[$row['name']][] = $row_dup2['comment'];
}
}
}
}
If the name has a duplicate, meaning it has more than one comment, still cant get my desired results.

You would have to check whether it already exists or not, and if it does, create an array (or do that from the start)
// Create arrays with names
$comment[$row['name']][] = $row['comment'];
or
// Check if there's an array
if (isset($comment[$row['name']])) {
if (is_array($comment[$row['name']])) {
$comment[$row['name']][] = $row['comment'];
} else {
$comment[$row['name']] = array($comment[$row['name']], $row['comment']);
}
} else {
$comment[$row['name']] = $row['comment'];
}
I should point out that the first solution would be very much preferred because it is a lot more consequent.

Yes, it is possible, but you need to do some preprocessing for that:
$comment = array;
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){
if(!isset($comment[$row['name']])) {
$comment[$row['name']] = array();
}
$comment[$row['name']][] = $row['comment'];
}
echo json_encode($comment);

Yes, it's possible. Instead of this line:
$comment[$row['name']] = $row['comment'];
Use this:
$comment[$row['name']] = array('Yo', 'Sup');
And replace the contents of the array with the greetings you want from the database.

Simple change:
$comment[$row['name']] = $row['comment'];
to
$comment[$row['name']][] = $row['comment'];
Each name element of the $comment array was being overwritten each time the same name came up.

Related

PHP data Loading Issue

I am designing a PHP service which fetches data for using it in android.
The issue is when I run the query with Where Clause (id < 30) it's working. but when I change (id <40) I am getting a blank screen:
$return_arr = array();
$fe = mysqli_query($conn,"SELECT id, name FROM cable_channels where id < 30;");
while ($row = mysqli_fetch_array($fe)) {
$row_array['id'] = $row['id'];
$row_array['name'] = $row['name'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
<?php
$return_arr = array();
$fe = mysqli_query($conn,"SELECT id, name FROM cable_channels where id < 30;");
while ($row = mysqli_fetch_assoc($fe)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>
Try above code, instead of using
mysql_fetch_array
use
mysql_fetch_assoc
and push all the values to array inside while loop.

Why is the query returning only one set of data?

The problem I have is when I echo or print the following variables, the data I receive is that of the last business listed in my table only.
At present no matter the listing I click I get the same set of data for the last business returned.
As you can see in the below code I am passing the business_name from the clicked listing to be used in my query to find the relevant business profile information.
$business_name = mysql_real_escape_string($_GET['business_name']);
$query = "SELECT
business_id,
category,
years_recommended,
profile_size,
business_name,
established,
employees,
service,
strengths,
ideal_for,
reassurance
FROM
business_data
WHERE
business_name = '$business_name'
AND
profile_size = 'A'
OR
profile_size = 'B'
OR
profile_size = 'C'
OR
profile_size = 'D'
OR
profile_size = 'E'";
$result = mysql_query($query, $dbc)
or die (mysql_error($dbc));
while($row = mysql_fetch_array($result)) {
$business_id = $row["business_id"];
$profile_size = $row["profile_size"];
$category = $row["category"];
$years = $row["years_recommended"];
$established = $row["established"];
$employees = $row["employees"];
$service = $row["service"];
$strengths = $row["strengths"];
$ideal_for = $row["ideal_for"];
$reassurance = $row["reassurance"];
}
echo...
If you need more information please let me know.
Is there anything wrong with my code?
Many thanks in advance.
Your echo call is outside the fetch loop, so you'll only see the last result even though the others were returned.
while($row = mysql_fetch_array($result)) {
$business_id = $row["business_id"];
$profile_size = $row["profile_size"];
$category = $row["category"];
$years = $row["years_recommended"];
$established = $row["established"];
$employees = $row["employees"];
$service = $row["service"];
$strengths = $row["strengths"];
$ideal_for = $row["ideal_for"];
$reassurance = $row["reassurance"];
// Echo **inside** the loop
echo...
}
If you wish, you can store all the results in a large array, which can then be used anywhere subsequently in your script, as many times as needed:
// Array for all results
$results = array();
while($row = mysql_fetch_array($result)) {
// Append each row fetched onto the big array
$results[] = $row;
}
// Now use it as needed:
foreach ($results as $r) {
echo $r['profile_size'];
print_r($r);
}
your echo should be inside the loop

How do I add data from two tables in mySQL and PHP?

I have a table with two fields, named credithour and gradepoint.
I want to add the data from each row of credithour with gradepoint.
My code :
$totalcredithour = 0;
$GPA = "SELECT * FROM $dept_stu_id WHERE sessionyear = '$sessionyear'" or die (mysql_error());
$resultGPA = mysql_query($GPA);
while($data = mysql_fetch_array($resultGPA))
{
$credithour = "$data[credithour]";
$gradepoint = "$data[gradepoint]";
echo $totalcredithour += $credithour;
}
What am I doing wrong?
It added data, but showing the first credit hour also besides result.
Suppose, here i entered two data 3 and 5. When I run this code it echo 38. Which means "3+5=8" and 1st credithour = "3".
Actually other answer are wrong, you're doing or die(mysql_error()); next to a string, that's not right.
Your code should be like this..
$totalcredithour = 0;
$GPA = "SELECT * FROM `".$dept_stu_id."` WHERE sessionyear = `".$sessionyear."` ";
$resultGPA = mysql_query($GPA) or die(mysql_error());
while($data = mysql_fetch_array($resultGPA, MYSQL_ASSOC))
{
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
echo $totalcredithour += $credithour; //Make sure `$totalcredithot` isn't null/doesn't exist.
}
try something like this in your while loop:
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
Try it like this
I have edited the answer and added the floatval function
$totalcredithour = 0;
$GPA = "SELECT * FROM `".$dept_stu_id."` WHERE sessionyear = '".$sessionyear."'" or die (mysql_error());
$resultGPA = mysql_query($GPA);
while($data = mysql_fetch_array($resultGPA))
{
$credithour = $data['credithour'];
$gradepoint = $data['gradepoint'];
echo $totalcredithour += floatval($credithour);
}

Can i make this simpler?

Hey,
im new to PHP (started last week)
ive got 10 lines of info in a SQLDB
im doing the same thing to all 10:
$db_line1 = mysql_query("SELECT * FROM messages WHERE message_id='1'");
$line1 = mysql_fetch_array($db_line1);
unset ($line1['0']);
unset ($line1['1']);
unset ($line1['2']);
$db_line2 = mysql_query("SELECT * FROM messages WHERE message_id='2'");
$line2 = mysql_fetch_array($db_line2);
unset ($line2['0']);
unset ($line2['1']);
unset ($line2['2']);
Etc. etc. all the way to $line10, could i use something like the "foreach" function?
$query = mysql_query("SELECT * FORM messages");
while($result = mysql_fetch_assoc($query))
{
echo "<pre>";
print_r($result);
echo "</pre>";
}
unset($result);
Answering to the comment ("can I get them in their own arrays"):
$query = mysql_query("SELECT * FORM messages") or die(mysql_error());
$messages = array();
while($result = mysql_fetch_assoc($query))
{
$messages[] = $result;
}
unset($result);
You can then iterate over the $messages.
EDIT following author's comment
Take all rows at once
$db_line = mysql_query("SELECT * FROM messages WHERE message_id >= '1'" .
" AND message_id <='10'");
$rows = array();
while ($line = mysql_fetch_assoc($db_line))
{
$rows[$line['message_id']] = $line;
}
This way you have an array of rows (ie an array of arrays).
To get the row for message_id 3, just do
$row = $rows[3];
and to access the (for instance) name column,
$row['name']
or
$rows[3]['name']
You may use dynamically created variables in php:
for ($i = 0; $i < 3; $i++){
unset(${'line'.$i});
}
EDIT:
How it works (example):
$var1 = "hel";
$var2 = "lo";
$hello = "xxx";
echo ${$var1.$var2}; // outputs "xxx"
Using ${'xyz'.$variable} will give you the variable with name 'xyz'.$variable. Notice that
"'xyz'.$variable" gets determined first.
$db_lines = mysql_query("SELECT * FROM messages");
while ($line = mysql_fetch_array($db_lines))
{
unset ($line['0']);
unset ($line['1']);
unset ($line['2']);
}

Add Additional Objects to JSON Encoded Array

I am currently using a JSON encoded array to display the users in my database for an auto-suggest feature.
It looks something like this:
$sth = mysql_query("SELECT id, name FROM users");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
print json_encode($data);
This returns:
[{"id":"81","name":"John Doe"},{"id":"82","name":"Jane Doe"}]
My question is somewhat 2-fold:
First, how would I manually add an additional object to this output? For example, let's say I wanted to add: {"id":"444","name":"A New Name"}
Thus, it'd look like:
[{"id":"81","name":"John Doe"},{"id":"82","name":"Jane Doe"},{"id":"444","name":"A New Name"}]
Second, let's say I also wanted to add more objects to the array from a separate table as well, such as:
$sth = mysql_query("SELECT id, title FROM another_table");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['title'];
$json['id'] = $row['id'];
$data[] = $json;
}
print json_encode($data);
This way I could have both tables populated in the JSON array, thus, showing up as additional options in my autosuggest.
Hopefully this makes sense, as I've tried hard to articulate what I am trying to accomplish.
Thanks!
Just keep pushing to the $data array.
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
$custom = array('name'=>'foo', 'id' => 'bar');
$data[] = $custom;
Then at the very end, do your json_encode. Assuming you're not referring to merging it in the JS itself with multiple ajax calls.
And if you have separate scripts, combine them in one php page.
Try in this way:-
$temp = json_encode($json); //$json={"var1":"value1","var2":"value2"}
$temp=substr($temp,0,-1);
$temp.=',"variable":"'.$value.'"}';
You could edit the JSON (text), but it's much easier to modify the array before you encode it.
Or am I missing something?
I'm not an expert in any of these fields, but I'll try and see if I can help. Try one of these:
Option 1 (I don't know how unions work in mysql):
$sth = mysql_query("SELECT id, name FROM users union SELECT id, name FROM (SELECT id, title as name from another_table) as T2");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
}
$json['name'] = 'A new name';
$json['id'] = '444';
$data[] = $json;
print json_encode($data);
I've never done PHP, so I'm making assumptions. I've also never used MySql, so there's more assumptions.
Option 2:
$sth = mysql_query("SELECT id, name FROM users");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
}
$sth = mysql_query("SELECT id, title from another_table");
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['title'];
$json['id'] = $row['id'];
}
$json['name'] = 'A new name';
$json['id'] = '444';
$data[] = $json;
print json_encode($data);
Hope this helps.

Categories