I am creating a json array in PHP like this (it's inside a class):
$STH = $DBH->query("SELECT ID,title,content FROM table WHERE ID= '".$ID."' ");
$querycount = $STH->rowCount();
if($querycount!=0):
$STH->setFetchMode(PDO::FETCH_OBJ);
while( $row = $STH->fetch()) :
$thread[$row->ID]['title'] = $row->title;
$thread[$row->ID]['content'] = $row->content;
endwhile;
$this->querycount = $querycount;
$this->thread = json_encode($thread);
else:
$this->querycount = $querycount;
endif;
But I seem to get "strange" decodes the other end. I cannot actually reference the array by key's;
So far it will let me do this: (Where af_threads is the class name and $key id the ID in the table query)
$threads = new af_threads($key,$DBH);
$threads = json_decode($threads->thread);
foreach($threads as $key1=>$thread):
foreach($thread as $key2=>$val):
echo $key2;
echo $val;
endforeach;
echo '<hr />';
endforeach;
But what it will not let me do is something like this
$threads[$key]['title']
I'm not sure why. As the class builds i.e. with more rows etc. I will need to call specific rows in specific places. i.e. $threads[$key]['newrow'], $threads[$key]['newrow2'], and or to manipulate a row with say substr(); etc.
Yes I know I could just echo out an array without json, but eventually I want to add cross domain functionality with JQuery getJSON() ...
Have I got it all wrong?
By default, json_decode() returns stdClass, modify second line with
$threads = json_decode($threads->thread, true)
and you will get an associative array and be able to reference it by keys, $threads[$key]['title'] for example.
Related
So I am getting the elements from the MySQL table and I want to make them into an array and then merge that array which gets encoded into JSON. It doesn't error but it only is displaying an empty JSON string'[]'
<?php
include "connectdb.php";
$banned = array();
$query = mysql_query("SELECT * FROM banned");
while($row = mysql_fetch_array($query)) {
$user = array(
UserId => $row["userId"],
Reason => $row["reason"],
);
array_merge($banned,$user);
}
echo json_encode($banned);
?>
It looks like you're just trying to add a $user array, which you're using as sort of an object, to the $banned array.
To push something onto an array, use array_push, or this notation:
$banned[] = $user;
Your php looks fine, so we are doen to your database or query. Put this line after your query:
echo mysql_num_rows($query);
See if this number is 0. If it is, you are not actually getting any information back from your query.
If that doesn't help locate the problem, keep using echo liberally, at ever line if you need to. See what is happening and why. This is the way you diagnose a problem. Echo the $row["userId"], echo the $banned variable before encoding, although that will take a var_dump(). Echo everything and you'll locate your problem.
First build a multi dimensional array, and encode it for JSON.
<?php
include "connectdb.php";
$banned = array();
$query = mysql_query("SELECT * FROM banned");
while($row = mysql_fetch_array($query)) {
$user = array(
UserId => $row["userId"],
Reason => $row["reason"],
);
$banned[] = $user;
}
echo json_encode($banned);
?>
Then if you need to, you can still access the array like this:
for ($i = 0; $i < count($banned); $i++) {
$UserID = $banned[$i]['UserID'];
$Reason = $banned[$i]['Reason'];
//Do something with this data like:
echo "User ".$UserID." was banned for ".$Reason;
}
I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>
I thought this was quite basic but for some reason I can't figure it out.
I have this query
$result = mysql_query("SELECT * FROM Users.Information LIMIT 0,1");
To grab the data (such as firstName, lastName), I use this snippet of code
<?php while ($row = mysql_fetch_assoc($result)): ?>
<?php foreach($row as $key=>$value) {
echo $value;
} ?>
<?php endwhile; ?>
which correctly prints everything I want.
Now in a separate table, I want to have it such that I will print the individual values separately. I thought this was quite simple like
first name:
however, this does not work. If I just do $value, of course this makes sense, but it prints the last value in the array.
How do I grab individual values? Do I just parse $value into different values, or is there an easier way?
Thank You.
$data = array() ; //Create a storage, so you can access it later.
<?php while ($row = mysql_fetch_assoc($result)): ?>
$data[] = $row ; //Add the value to storage.
<?php foreach($row as $key=>$value) {
echo $value;
} ?>
<?php endwhile; ?>
We are ready. We have $data array with all rows. Now you can manipulate it, access elements, pass somewhere.
$data[0] ; //Access the first element
echo $data[0]['FirstName'] ; //Print first name of the first row.
What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}
I want to add a bit more information to a json object before sending it back to my app.
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
echo '{"items":'. json_encode($res) .'}';
The PDO query returns a result set like this when I echo($res)
Array{"items":[{"uid":"10","repo":"bnef"}]}
then it gets encoded back to jquery- echo '{"items":'. json_encode($res) .'}';
giving me
{"items":[{"uid":"10","repo":"bnef}]}
I'd like to add "isnew":"1" to that but when I try
$res['isnew']="1"; or array_merge I end up with
{"items":{"0":{"uid":"10","repo":"bnef"},"isnew":"1"}}
which doesn't work. I need
{"items":[{"uid":"10","repo":"bnef, "isnew":"1"}]}
Am I misguide in try to do this?
I misread your question and got confused on the code... you shoudl incat be dealign with an array initially try the following:
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$items = $q->fetchAll(PDO::FETCH_OBJ);
// you actually wnt isnew as a property of each row
// so you need to loop over the results
foreach($items as $key => $item){
$item->isnew = 1;
}
echo json_encode(array(
'items' => $items
));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
Its not working because you used FETCH_OBJ instead of FETCH_ASSOC so youre wokring with an StdObject instance not an array. In that case you need to use -> to assign:
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res->isnew = "1";
Alternatively you could fetch as an associative array:
$res = $q->fetchAll(PDO::FETCH_ASSOC);
$res['isnew']="1"; //this will work now
Additionalyl i wouldnt try to manipulate the JSON serialized string. I would doo all modifications natively:
$items = array(
'items' => $res
);
echo json_encode($items);