php msql sort values by name - php

I'm struggling a bit with the new mysql/php code, I have a sniplet which picks out all my books, but I would like to sort it by the author. (row[1])
$db=new mysqli("$dbhost","$dbuser","$dbpass");
$db->select_db("$dbname");
$query="select * from book";
$result=$db->query($query);
//find number of rows
$num_rows=$result->num_rows;
for($i=0;$i<$num_rows;$i++)
{
//fetch row
$row=$result->fetch_row();
$total=$total+$row[2];
echo "<tr>";
echo "<td><a href='http://isbndb.com/search/all?query=".$row[8]."'>$row[4]</td>" ;
echo "<td>$row[1]</td>" ;
echo "<td>$row[10]</td>" ;
echo "<td>$row[9]</td>" ;
$stoke=$row[2]-$row[3];
$tstoke=$tstoke+$stoke;
$tout=$total-$tstoke;
echo "<td width=\"30\">$stoke</td>" ;
echo "</tr>";
}
how does one do this?

you can use this in your query after your select
$query="select * from book ORDER BY author";
//or
$query="select * from book ORDER BY author DESC";
Avoid using * try mentioning the field names (i.e.)
$query="select id,books,author,etc from book ORDER BY author";
further reference here

$query="select * from tablename order by coloumnname ASC or DESC";
where you can choose your condition ASC or DESc

Related

How can i display the 5 latests results from the database at the bottom of the page in PHP instead of displaying it at the top?

This is my PHP file:
<?php
$sql = "SELECT * FROM `general_chat` ORDER BY `general_chat`.`id` DESC limit 5";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "<p>";
echo "<span class = 'usr'>".$row['user_name']."</span>";
echo "<br>";
echo $row['message'];
echo "<br>";
if($row['Date'] === date("Y-m-d")){
echo "Today ";
}
else{
echo $row['Date'];
}
echo $row['Time'];
echo "</p>";
}
}
else{
echo "No messages were found!";
}
?>
This is how my database table looks:
An image of the database table
And this is how it displays the data in the PHP file:
An image of the PHP file output
It displays the five latest rows at the top, is it possible to flip and make it display it at the first bottom and then display the others on top of it?
I tried using DESC instead of ASC but then it displays the five oldest rows instead of the latest
I am not sure this is a perfect method
but this could solve your problem
select * from (SELECT * FROM `general_chat` ORDER BY `general_chat`.`id` DESC limit 5) G ORDER BY G.id ASC;
This IS wrapping your SQL with a similar one
so in subquery it will fetch all latest 5 items and in main query it will sort by ASC
Try :
$sql = "SELECT * FROM (SELECT * FROM `general_chat` ORDER BY `general_chat`.`id` DESC limit 5) as G ORDER BY `G`.`id` asc";

How to mysqli_fetch_row while using mysqli_multi_query

I'm trying to get the latest info about some specific person, and I'm using a query like
SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID DESC LIMIT 1
and
SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID DESC LIMIT 1
because in the Table each day will insert new data for different person at the instant of updating it (for record reference), so I would like to print out a few persons latest info by "ORDER BY ID DESC LIMIT 1"
I have tried to print it out with "mysqli_multi_query" and "mysqli_fetch_row"
like
$con=mysqli_connect($localhost,$username,$password,'Table');
$sql = "SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID
DESC LIMIT 1 ";
$sql .= "SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID
DESC LIMIT 1";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo '<tr>'; // printing table row
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>'.$row[2].'</td>';
echo '<td>'.$row[3].'</td>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[5].'</td>';
echo '<td>'.$row[6].'</td>';
echo '<td>'.$row[7].'</td>';
echo '<td>'.$row[8].'</td>';
echo '<td>'.$row[9].'</td>';
echo '<td>'.$row[10].'</td>';
echo '<td>'.$row[11].'</td>';
echo '<td>'.$row[12].'</td>';
echo '<td>'.$row[13].'</td>';
echo '<td>'.$row[14].'</td>';
echo'</tr>'; // closing table row
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
In the result page , it doesn't show any error message , but no results are printed.
The individual queries were tested.
Please advise, much thanks
Is there another way to keep the query simple, so there is no need to use mysqli_multi_query?
Best practice indicates that you should always endeavor to make the fewest number of calls to the database for any task.
For this reason, a JOIN query is appropriate.
SELECT A.* FROM test A INNER JOIN (SELECT name, MAX(id) AS id FROM test GROUP BY name) B ON A.name=B.name AND A.id=B.id WHERE A.name IN ('Peter','Mary')
This will return the desired rows in one query in a single resultset which can then be iterated and displayed.
Here is an sqlfiddle demo: http://sqlfiddle.com/#!9/2ff063/3
P.s. Don't use LIKE when you are searching for non-variable values. I mean, only use it when _ or % are logically required.
This should work for you:
$con = mysqli_connect($localhost,$username,$password,'Table');
// Make a simple function
function personInfo($con, $sql)
{
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<table>
<tr>';
for($i=0; $i < count($row); $i++) echo '<td>'.$row[$i].'</td>';
echo '</tr>
</table>';
}
}
}
$sql1 = "SELECT * FROM Table WHERE Name='Peter' ORDER BY ID DESC LIMIT 1 ";
$sql2 = "SELECT * FROM Table WHERE Name='Mary' ORDER BY ID DESC LIMIT 1";
// Simply call the function
personInfo($con, $sql1);
personInfo($con, $sql2);

How to make SQLite query that sorts by several conditions, and works in PHP

Can anyone point me how to write SQLite query with multiple sorts, that will work in PHP?
Now I have:
SELECT *
FROM Articles
ORDER BY Published DESC, Date DESC, Time DESC
Other example is:
SELECT *
FROM Articles
ORDER BY DateTimeLastEdited DESC, DateTimeCreated DESC
Articles is TEXT, Published is BOOL (0 or 1), and both Date and Time are TEXT (date and time entries).
What is confusing me is that when I test the query directly in SQLite client, it works. However, using it in PHP doesn't sort it as it does in SQLite client!
What would be the right syntax to sort by multiple conditions, and is there a reliable SQLite query testing tool for PHP use? (The PHP used is 5.5.3)
To use SQLite simply in PHP you can use PDO object. Here is a good tutorial about it.
To sort multiple condition:
You could use e.g. ORDER BY rating DESC, name ASC to sort by rating and then, if the ratings are equal, by name.
I have made the stupidest error. :-(
In the end, it turned out it was not the SQL code, but missing = in PHP. SQL queries were OK, but the IF / ELSE IF I have used were missing one "=".
My code contained = instead of == for condition checking, and as I was focused on SQL query I completely missed. Here is the full code:
function display_all_Articles_in_a_HTML_table($sort = "ID")
{
if ($sort == "ID")
{
$sql = "SELECT * FROM Articles ORDER BY ID DESC";
}
else if ($sort == "DateTime")
{
$sql = "SELECT * FROM Articles ORDER BY Date DESC, Time DESC";
}
else if ($sort == "DateTimeCreated")
{
$sql = "SELECT * FROM Articles ORDER BY DateTimeCreated DESC";
}
else if ($sort == "DateTimeLastEdited")
{
$sql = "SELECT * FROM Articles ORDER BY DateTimeLastEdited DESC, DateTimeCreated DESC";
}
else if ($sort == "Published")
{
$sql = "SELECT * FROM Articles ORDER BY Published DESC, Date DESC, Time DESC";
}
else
{
return FALSE;
}
//
//DB fetch, returns $result
//
$result = retrieve_from_database($sql);
//
//Print sorted HTML table
//
print '<table border="1">';
foreach($result as $position_in_main_array => $inner_array_member)
{
echo "<tr>";
echo "<td>";
echo $inner_array_member["Date"];
echo "</td>";
echo "<td>";
echo $inner_array_member["Time"];
echo "</td>";
echo "<td>";
echo $inner_array_member["Published"];
echo "</td>";
echo "<td>";
echo $inner_array_member["Article"];
echo "</td>";
echo "<td>";
echo $inner_array_member["DateTimeCreated"];
echo "</td>";
echo "<td>";
echo $inner_array_member["DateTimeLastEdited"];
echo "</td>";
}
echo "</table>\n";
}
**
There is also another way to get the same SQLite result:
SELECT * FROM (SELECT * FROM (SELECT * FROM Table ORDER BY Column DESC) ORDER By Column DESC), ORDER BY Column DESC
I played a bit with it, trying to find query that would work, while I was thinking that PHP built-in SQLite was a bit weird.
Thanks to all who replied.

How to echo random data

I have the following code, that outputs all data from the comment field, however i wish for it to output only two and for them to be random, how can i got about doing this? many thanks.
$query = mysql_query("SELECT * FROM comments ");
//query the database
echo "<b>Reviews</b> ";
WHILE($rows = mysql_fetch_array($query)):
$comment_by = $rows['comment_by'];
$comment= $rows['comment'];
echo "<div style ='font:14px/21px Arial,tahoma,sans-serif;color:#cf5c3f </h>'>$comment_by</h>";
echo "<div style ='font:14px/21px Arial,tahoma,sans-serif;color:#ff0000 <h></h>'>$comment<br><br>";
endwhile;
?>
Use:
SELECT * FROM comments
ORDER BY RAND()
LIMIT 2
LIMIT 2: for two records
and
ORDER BY RAND(): for random comments
See official MySQL documentation:
ORDER BY: https://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
RAND(): https://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html
LIMIT: https://dev.mysql.com/doc/refman/5.0/en/select.html
From dev.mysql.com
$query = mysql_query("SELECT * FROM comments ORDER BY RAND() LIMIT 2");

only echoing the last 4 things inserted into a MYSQL database

ive got this script that echos the information from a mysql database.
now it all works fine but i only want to echo the last 4 statements inserted
this is the script
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("blog") or die(mysql_error());
$result = mysql_query("SELECT * FROM blog")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['username'];
echo "</td></tr>";
}
echo "</table>";
?>
Modify your mysql query (i assume that each entry as an ascending id):
SELECT * FROM blog
ORDER BY id DESC
LIMIT 4;
But this will get them in reverse order. If you want them in correct order you can do:
SELECT *
FROM (
SELECT * FROM blog
ORDER BY id DESC
LIMIT 4
) last_four
ORDER BY id ASC;
If you have an auto-incremented column as an id for each blog post, you could sort on the id in descending order. Use a query like this
mysql_query("SELECT * FROM blog ORDER BY your_id_column DESC LIMIT 4")
Assuming your blog table has a column called created, which contains the post's creation date, this query should do what you need:
SELECT * FROM blog ORDER BY created DESC LIMIT 4
This will order your posts by the most recently created post (time-wise), and will only return the first 4 rows fetched from the table.
You would do this with the query, changing the query to something like:
select * from blog order by blog_id desc limit 4
you'll have to change blog_id to whatever you use.
use this query which will order the records by ID in descending order and fetch only last 4 by using limit.
SELECT * FROM blog order by ID DESC LIMIT 4
You can restrict your SELECT using LIMIT and ORDER BY, but in order to help, we'd need to know a bit more about the database structure. Can you provide the results of "DESCRIBE blog;"?
If your "id" field is set up with auto_increment, then it's a good bet that higher numbers of that field indicate more recent posts. Showing output in reverse order ("ORDER BY id DESC") and restricting the number ("LIMIT 4") should be fairly straightforward.
SELECT * FROM blog ORDER BY id DESC LIMIT 4;
Check out the precise structure of the SELECT command at the MySQL documentation.
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("blog") or die(mysql_error());
$result = mysql_query("SELECT * FROM `blog` ORDER BY `id` DESC LIMIT 4") or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['username'];
echo "</td></tr>";
}
echo "</table>";
?>
Just copy and paste the code. I believe the code will works good. Thanks

Categories