PHP - How to sort Array from MySQL database - php

I am retrieving data from a MySQL database with mysqli. I am retrieving rows from the data base, the database has a name and a number for that name and I need the name with the highest number to be printed first, the name with the second highest number to be printed second, and so on...
Here is my code
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
printf ("%s (%s)\n", $row["name"], $row["goals"]);
}
Here is the current output
and I need it so that KaminJack is printed first , BregmanMichael is printed second, and so on

Your query should be:
SELECT * FROM mytable ORDER BY goals desc
Find your data then order by the field goals sorting desc (or asc if you want to).

To further improve on the answer, you should order by two columns as you have some names with the same number: HidiJack (0) and JainAJesh(0).
SELECT * FROM mytable ORDER BY goals desc, name asc;
This will order by the number first, then alphabetically by name.
Or better if you can, make the number an index so that you don't have duplicates.

First of all, you could use simply ORDRE BY in MySQL to sort.
But if you want to do it in php:
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$result[$row["name"]] = $row["goals"];
}
arsort($result);
http://www.php.net/manual/en/function.arsort.php

Related

PHP get first row from SQL database

In a table I am developing, you can see that there is a person with the best known time. I would like to show it in my page, and so I used this code:
$con=mysqli_connect("localhost","user","pass","database");
if( $result2 = mysqli_query($con,"SELECT playername FROM 1_toad_circuit /*name of the table*/ LIMIT 0 , 30") ) {
$row = mysqli_fetch_row($result2);
printf ("%s \n", $row[0]);
}
As output I am not getting Itoi6 (person with the best time), but I have Catfish (the first in alphabetical order). I have 3 columns as you can see on the picture (link).
I say that I am pretty new with SQL and I would like to know what do I have to fix.
You need to add an ORDER BY clause to your statement and then order by whichever field you are storing the times in.
For example, if you had a "time" field:
SELECT playername, time FROM 1_toad_circuit
ORDER BY `time` ASC
LIMIT 1

MySQL row selection

I have a table as below,
ID Name Age
----------------------
100 A 10
203 B 20
Now how do i select only row1 using MySQL SELECT command and then I've to increase +1 to it to select row2. In short I'll be using for loop to do certain operations.
Thanks.
Sounds like you've got a mix up. You want to select all the rows you want to iterate through in your for loop with your query, and then iterate through them one by one using php's mysql functions like mysql_fetch_row
You should not try to use tables in a linear fashion like this. Set your criteria, sorting as appropriate, and then to select the next row use your existing criteria and limit it to one row.
SELECT * FROM `table` ORDER BY `ID` LIMIT 1
SELECT * FROM `table` ORDER BY `ID` WHERE ID > 100 LIMIT 1
You'd probably be better off retrieving all rows that you need, then using this. Note the LIMIT is entirely optional.
$query = mysql_query(' SELECT ID, Name, Age FROM table_name WHERE condition LIMIT max_number_you_want '))
while ($row = mysql_fetch_assoc($query)
{
// Do stuff
// $row['ID'], $row['Name'], $row['Age']
}
Lots of small queries to the database will execute much slower than one decent-sized one.
You should get the result into an array (php.net : mysql_fetch_*).
And after you'll can loop on the array "to do certain operations"
Yep, this is a pretty common thing to do in PHP. Like the others who have posted, here is my version (using objects instead of arrays):
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_object($result)) {
// Results are now in the $row variable.
// ex: $row->ID, $row->Name, $row->Age
}

How do I fetch the last record in a MySQL database table using PHP?

I want to fetch the last result in MySQL database table using PHP. How would I go about doing this?
I have 2 Columns in the Table, MessageID(auto) & Message.
I already know how to connect to the database.
Use mysql_query:
<?php
$result = mysql_query('SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo $row['messageid'];
echo $row['message'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
The SQL query:
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
...uses the ORDER BY to set the values so the highest value is the first row in the resultset. The LIMIT says that of all those rows, only the first is actually returned in the resultset. Because messageid is auto-increment, the highest value is the most recent one...
Records in a relational database do not have an intrinsic "order" so you cannot fetch the "last" record without some kind of ORDER BY clause.
Therefore, in order to fetch the "last" record, simply reverse the ORDER BY clause (change ASC to DESC or vice versa) then select the first result.
If you have an auto-increment field and you just want to find the last value that was inserted, you can use the fact that the auto-increment fields are ever-increasing (therefore the "last" one will be the one with the highest value) and do something like this:
SELECT *
FROM my_table
ORDER BY id_field DESC
LIMIT 1
Of course you can select the last row by sorting DESC in your query. But what if you want to select the first row and then the last. You can run a new query, but you can also use the function mysql_data_seek. check code below:
$result = mysql_query('YOUR QUERY') or die('Invalid query: ' . mysql_error());
$row_first = mysql_fetch_array($result);
mysql_data_seek($result , (mysql_num_rows($result)-1));
$row_last = mysql_fetch_array($result);
Hope this helps
The MySql query would look like this:
select MessageID, Message
from Table
order by MessageID desc
limit 1;
I am too rusty with PHP to give you the right syntax for executing this.
This query works because you have an auto-incrementing identifying field (MessageID). By ordering the results by that field in descending (largest to smallest) order we are effectively returning the records in the table in reverse order. The limit 1 clause simply limits the result set to one record - the last one in the table.
What do you mean by "the last result"? You need to precise a bit more.
Do you mean "the last entry I registered"?
In this case you should use the appropriate method (depending on the extension you are using) mysqli->insert_id OR mysql_insert_id.
If you mean "the latest entry in the table", an SQL query such as Andrew Hare's is just what you need.
Do you mean the last record or do you need the id of the most recently inserted record? For that you would use the PHP mysql_insert_id() function. Or if you are using the myusqli extension use $mysqli->insert_id.
for some reason (which I don't know why), my boss force me to get the data in this way:
$message_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$message_arr['messageid']= $row['messageid'];
$message_arr['message']= $row['message'];
}
return $message_arr;
Of course, you need everything from OMG Ponies's answer I'm just telling you another way to do it =)
I hope this help.
You should use SELECT query. How SELECT works.
SELECT * FROM table - selects everything in a table (id, row 1, row 2,...)
SELECT id FROM table - selects only particular row from table.
If you now know, how to select, you can use additional logic.
SELECT * FROM table ORDER by id DESC LIMIT 1;
selects everything from table table, orders it by id - orders it DESCENDING and limits the query to only one result.
If you would do it like this:
SELECT * FROM table ORDER by id ASC limit 1; - you would get 1 entry into database.
You can order it by any row you want.
Hope it helps.
One thing to remember is that data does not get saved in the insertion order in any MYSQL database. So in order to get the last entered record u will have to have an auto increment field. Since there is an auto increment field in this table we are good to go.
The below script will help to get the last entered record
<?php
$sql = "SELECT * FROM table_name ORDER BY MessageID DESC LIMIT 2";
$result_set = mysql_query($sql);
if($result_set){
while($row = mysql_fetch_array($result_set)) {
echo "Message Id: ".$row['MessageID']."<br>";
echo "Message: ".$row['Message']."<br>";
}
//creating alert
echo "<script type=\"text/javascript\">alert('Data was Retrieved
successfully');</script>";
}
else{
//creating alert
echo "<script type=\"text/javascript\">alert('ERROR! Could Not Retrieve
Data');</script>";
}
?>
The query selects all the records in the table and orders them according to the descending order of the MessageID (as it is the auto increment field) and limits the returned result to only one record. So since the table is ordered according to the descending order of the MessageID only the last entered record will be returned.
NOTE: if you are using a newer version you will have to use mysqli_query($connection_variable,$sql); instead of mysql_query($sql); and mysqli_fetch_array($result_set) instead of mysql_fetch_array($result_set)
$result = mysql_query('select max(id) from your_table ') or die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['id'];
echo $row['message'];
}
//
//
mysql_free_result($result);
simple like that
this code of php works fine
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
if you don't have concurrent entries going into some table.b'cause concurrent entries may not go in accordance of their insertion order.
$statement = $PDO->prepare("
SELECT MessageID,
Message
FROM myTable
ORDER BY MessageID DESC
LIMIT 1;
");
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
echo $result['MessageID']." and ".$result['Message'];

Order MySQL results by number of related rows in foreign table

Alright, so I have a table outputting data from a MySQL table in a while loop. Well one of the columns it outputs isn't stored statically in the table, instead it's the sum of how many times it appears in a different MySQL table.
Sorry I'm not sure this is easy to understand. Here's my code:
$query="SELECT * FROM list WHERE added='$addedby' ORDER BY time DESC";
$result=mysql_query($query);
while($row=mysql_fetch_array($result, MYSQL_ASSOC)){
$loghwid = $row['hwid'];
$sql="SELECT * FROM logs WHERE hwid='$loghwid' AND time < now() + interval 1 hour";
$query = mysql_query($sql) OR DIE(mysql_error());
$boots = mysql_num_rows($query);
//Display the table
}
The above is the code displaying the table.
As you can see it's grabbing data from two different MySQL tables. However I want to be able to ORDER BY $boots DESC. But as its a counting of a completely different table, I have no idea of how to go about doing that.
There is a JOIN operation that is intended to... well... join two different table together.
SELECT list.hwid, COUNT(log.hwid) AS boots
FROM list WHERE added='$addedby'
LEFT JOIN log ON list.hwid=log.hwid
GROUP BY list.hwid
ORDER BY boots
I'm not sure if ORDER BY boots in the last line will work like this in MySQL. If it doesn't, just put all but the last line in a subquery.
But the result of the query into an array indexed by $boots.
AKA:
while(..){
$boot = mysql_num_rows($query);
$results[$boot][] = $result_array;
}
ksort($results);
foreach($results as $array)
{
foreach($array as ....)
{
// display table
}
}
You can switch between ksort and krsort to switch the orders, but basically you are making an array that is keyed by the number in $boot, sorting that array by that number, and then traversing each group of records that have a specific $boot value.

saving a column in an array

I'm trying to fetch random no. of entries from a database by using
SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10
it returns a column of database.
If I want to save all the entries in a array, then which php function do I have to use to save the column.
Something along the lines of this?
$result = mysql_query("SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10");
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row[0];
}
Updated to not use the $i variable as pointed out in the first post and the comment.
Look at some examples for how to run a query and get a result set.
http://www.php.net/mysqli
Once you have the result in a variable, do this:
$myarray = array();
while($row = mysqli_fetch_row($result))
$myarray[] = $row[0];
With PDO:
$qryStmt = $dbc->query('SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10');
$a = $qryStmt->fetchAll( PDO::FETCH_COLUMN );
BTW: If you just want to get one row by random, this is much faster esp. for large tables:
select * from table limit 12345,1;
where 12345 is just a random number calculated from the count() of rows.
see here, which is more for rails, but have a look at the comments too.
But be careful: in limit 12345,2 - the second row is not random but just the next row after the random row. And be careful: When I remember right (eg. SQLServer) rand() could be optimized by databases other than mysql resulting in the same random number for all rows which makes the result not random. This is important, when your code should be database agnostic.
a last one: do not mix up "random" with "hard to predict", which is not the same. So the order by example "select top 10 ... order by rand()" on SQLServer results in two different result sets when run twice, BUT: if you look at the 10 records, they lie close to each other in the db, which means, they are not random.

Categories