Live sort query results in php - 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.

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

echo in reverse order from mysql_fetch_assoc()

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

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

Print mysql results column by column

I feel incredibly stupid for not being able to figure this out, but I guess that's what Stackoverflow is for. If someone could point me to helpful resources or explain to me how to solve this, I would be very appreciative.
Basically I'm fetching a couple of rows from a table, and now I need to be able to print them out the value of each row's field, followed by the values of each row from a different field, and so on. It's hard to explain, but let me give you an example.
Let's say we have a table with three fields: id - name - url. Now I want to be able to output the result in this order:
1
2
3
John
Steven
Patrick
http://google.com/
http://stackoverflow.com/
http://php.net/
How do I loop through the results of my query in order to achieve this?
Well you should make an array and then spew it out:
$ids = array();
$names = array();
$urls = array();
while($row = ...){
$ids[] = $row['id'];
$names[] = $row['name'];
$urls[] = $row['url'];
}
foreach($ids as $id) {
echo $id . PHP_EOL;
}
//do the same for the other 2
You can do this via union. The only tricky part is making sure to cast all of the fields to a common data type (in this case, text). Also, each subquery is ordered by id to make sure that the ordering is consistent.
select id::text
from table
order by id
union
select name::text
from table
order by id
union
select url::text
from table
order by id
$result = mysql_query("SELECT id, name, url FROM yourtable") or die(mysql_error());
$data = array()
while($row = mysql_fetch_asssoc($result)) {
$data[] = $row;
}
foreach(array('id', 'name', 'url') as $key) {
foreach($data as $idx => $val) {
echo $val[$key], "\n";
}
}
The simplest way is
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$ids[] = $row['id'];
$names[] = $row['names'];
$wwws[] = $row['website'];
}
Then you iterate over the three arrays. There are surely better methods for doing this!

Display results from a query with PHP (Wordpress)

Trying to display results from an sql query in PHP:
SELECT *
FROM wp_celebcount
ORDER BY count DESC
I'm trying to display two columns: wp_celebcount.name & wp_celebcount.count
Having trouble getting the result to show with PHP - I want to show this result on my index.php Wordpress theme file. Thanks for the help...
If you're using Wordpress, it would be something like this:
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount');
foreach($result as $row) {
echo 'Name: '.$row->name.', Count: '.$row->count.'<br/>';
}
It's recommended to use the $wpdb global as it takes care of all the database setup for you.
More information on $wpdb can be found here.
mysql_fetch_assoc
Presuming you've done something like
$resultSet = mysql_query('SELECT * FROM wp_celebcount ORDER BY count DESC');
You should be able to pull out the results with
while ($row = mysql_fetch_assoc($resultSet))
{
var_dump($row);
//print an element named 'name' with echo $row['name'];
}

Categories