echo in reverse order from mysql_fetch_assoc() - php

Ok here's the trick.
In the query I'm getting the right results from a table named messages. (Its fetching the last 10 messages ordered by the time inserted in reversed order) here's the query:
$query = mysql_query("SELECT time, username, message
FROM messages ORDER BY time DESC LIMIT 10");
And than later those messages are printed inside div via ajax with
while ($item = mysql_fetch_assoc($query)) {
echo $item['time']." - ".$item['username']." - ".$item['message'];
}
But the printed result I want to print them only in the reversed order.
Tip: If I use ASC in the ORDER BY clause I don't get the last inserted messages.
Is this possible to do inside php?

Store your data & than use array_reverse,
while($row = mysql_fetch_assoc($result)){
$items[] = $row;
}
$items = array_reverse($items ,true);
foreach($items as $item){
echo $item['time']." - ".$item['username']." - ".$item['message'];
}

I would use a subquery personally. Im kinda anal about having my data come out of MySQL exactly how I want it, but the array_reverse method will work fine too. Here is my example:
$query = mysql_query("SELECT * FROM (
SELECT time, username, message
FROM messages ORDER BY time
DESC LIMIT 10) result
ORDER BY time ASC
");

Use: array_unshift - Prepend one or more elements to the beginning of an array
$items = array();
while($row = mysql_fetch_assoc($result)){
array_unshift($items,$row);
}
foreach($items as $item){
echo $item['time']." - ".$item['username']." - ".$item['message'];
}
Heres a useless but quick example. I hope it's still there: Simple example

Related

PHP Multi Dimensional Array Sorting

Edit : I need it to do only in Array Sort, As i am using procedure and sending it into json,
Here is my Table Structure,
SQL Fiddle
I want to display as
alpha london
alpha newyork
beta delhi
beta sydney
I mean, the second coloumn (name) should be in Ascending Order and the third coloumn (place) should be in Descending Order.
How i want is
alpha london
alpha newyowk
beta delhi
beta sydney
The Name should be in Asc Order and then to the right, the Place should be in Desc Order
What i have tried so far is
How can i do this ??
<?php
include ('conn.php');
$sql="SELECT * FROM test";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
while($rows=mysql_fetch_array($result))
{
foreach($result as $k=>$v)
{
echo $k;
}
}
?>
It displays the result as Invalid argument supplied to for each. What is the mistake i am doing and how can achieve my output
To fix the sorting, just add ORDER BY name, place
Then there's several more issues preventing this from working:
You shouldn't call mysql_fetch_array outside the loop (this would discard the first row, alpha london in your example).
You need to iterate over $rows, not $result (this is where the "invalid argument" error is coming from).
You're not echoing the value; only the key. So you wouldn't be displaying the name and place at all; only the words "name" and "place".
You might want to do something like this to fix these:
<?php
include('conn.php');
$sql = "SELECT * FROM test ORDER BY name, place";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result)) {
foreach ($rows as $k => $v) {
echo "$k is $v. ";
}
echo "<br/>";
}
?>
So why don't you do an order in your query itself like
SELECT * FROM test order by name;
You can do this only modifying query.
Use this query:
SELECT * FROM test ORDER BY name ASC, place DESC
For your error, you are using wrong variable as foreach.
Replace this -
foreach($result as $k=>$v)
{
echo $k;
}
with this -
foreach($rows as $k=>$v)
{
echo $k;
}
Buy why are using foreach inside while loop. You can get your values like -
while($rows = mysql_fetch_array($result)) {
echo $rows['name'].' '.$rows['place'].'<br/>';
}
and don't use mysql_* function. Use instead mysqli_*
And for your expected output, try using following query -
SELECT * FROM `test` order by name asc, place desc
This is the kind of thing you can fix using array_multisort.
Try the below example (which I have not tested yet, but ought to work)
<?php
include ('conn.php');
$sql="SELECT * FROM test";
$result=mysql_query($sql);
$totals = array();
$row = array();
$places = array();
while($row=mysql_fetch_array($result)){
$totals[] = $row
$names[] = $row['name'];
$places[] = $row['place'];
}
array_multisort( $names, SORT_ASC, $places, SORT_DESC, $totals );
// now you can use $totals, which is sorted as you want
print_r( $totals );

why single sql query is not working on multiple while () loop?

I don't know why it's behaving like that in Php. In my first while() loop its showing data but second and third while() loop it's not return/showing any data. I'm using only one sql query to get same data 3 times.
Do you know why it's not showing data in second and third while loop in php ?
$query = mysql_query("SELECT * FROM contact_details ORDER BY family_name LIMIT 10");
while($a=mysql_fetch_array($query)){
echo $fname = $a['family_name'];
echo "<br/>";
}
while($b=mysql_fetch_array($query)){
echo $fname = $b['family_name'];
echo "<br/>";
}
while($c=mysql_fetch_array($query)){
echo $fname = $c['family_name'];
echo "<br/>";
}
If you need to use the same result multiple times, store it in a local array first. Once your first loop is completed, there is obviously 'no more data left' as otherwise the while wouldn't have stopped.
For example:
$query = mysql_query("SELECT * FROM contact_details ORDER BY family_name LIMIT 10");
$data = [];
while($row = mysql_fetch_array($query))
$data[] = $row;
foreach($data as $row)
// Do Stuff;
foreach($data as $row)
// Do Stuff;
foreach($data as $row)
// Do Stuff;
Mandatory disclaimer: the mysql_ family of functions is deprecated and will start breaking in future PHP versions. Consider switching to PDO or mysqli.
From PHP docs, mysql_fetch_array returns "Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows" , so second and third loop reuturns FLASE (no more data )
Because the array pointer has reached the end it is not possible to read it again.
you can use
mysql_data_seek ( resource $result , int $row_number );
mysql_data_seek ( $query , 0 );
i suggest that after every while loop try to reset the pointer to this query using this
mysql_data_seek($query, 0); // add this after every while loop.
//you need this to reset the pointer of the query.
try this out and check back if you still have problems.
this link has your same problem and is already answered PHP - Multiple while($row = mysql_fetch_array($variable)) { } ERRORS

How do I insert values into an multidimensional-array, then show them?

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.
?>

Extract a specific value from this data type

I'm using this script to get data from a database
$sql = "SELECT * FROM items WHERE catid = 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row['extra_fields'];
}
The output is:
[{"id":"1","value":"johndoe"},{"id":"2","value":"marydoe"}]
I want to extract/print only the value corresponding to "id":"1" (that in this case is 'johndoe'). I'm not able to extract it from the above data type.
To read JSON in PHP use
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields'];
// Do something with $array['id']
}
Did you realise you can directly go for that data in MySQL?
SELECT value FROM items WHERE id = 2;
edit:
Basically your query is
SELECT comma-separated column names or star for all, use only what you really need to save bandwidth, e.g. SELECT id, value
FROM table-name, e.g. FROM mytable
WHERE columnname = desired value, e.g. WHERE id = 2
You want to query only the required columns in the required rows. Imagine one day you would have to parse 1 million users every time you want to get an id... :)
The output is JSON. Use PHP's json_decode function.
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
foreach($array AS $item) {
echo $item['id'];
}
}
Currently this is the code that fits my needs:
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
$value = $array[0]->value;
}
You should do it in the mysql query part. For example, set the ID = 1 in the query.

Live sort query results in php

I have a query which goes through the table and outputs the data like this:
Query
$query = mysql_query("SELECT * FROM `products`");
while($row = mysql_fetch_assoc($query)){
$array[] = $row;
}
foreach ($array as $key) {
$name[] = $key['name'];
$desc[] = $key['desc'];
$cost[] = $key['price'];
}
$c = 0;
while($c<(count($array))){
echo 'Name: '.$name[$c].'<br>';
echo 'Desc: '.$desc[$c].'<br>';
echo 'Price: '.$cost[$c].'<br><br>';
$c++;
}
Results
Name: xyz1
Desc: asdxsadasda
Price: 999
Name: xyz2
Desc: asdxsadasda
Price: 333
Name: xyz3
Desc: asdxsadasda
Price: 666
I want to be able to sort these results based on the price of each item.
Can I output the result in a jSON file and use that to sort the results (live-without loading the page)?
Could you suggest me a better way to sort the results without having to load the page?
If you MUST sort the array in PHP, after you got the query result, use the array_multisort function in PHP (http://www.php.net/manual/en/function.array-multisort.php)
However, if your life does not depend on sorting in PHP, sort at the source in your SQL (the way God intended it to be) it's going to be much much faster and it will take the load off the web server.
Hope this helps.
$query = mysql_query("SELECT * FROM `products` WHERE `category` order by products.price, products.name");
You choose sort by ASC or DESC
SELECT * FROM `products` order by price, name
Also, your foreach is not needed as you can do your array setup in the while loop.

Categories