mysql output sort order - php

I am using a PHP / MySQL pagination script which works fine, however I have trouble sorting the output accordingly.
Here parts of my script:
$link=mysql_connect("localhost","x","x");
mysql_select_db("x",$link);
$q="select count(*) \"total\" from entries";
$ros=mysql_query($q,$link);
$row=(mysql_fetch_array($ros));
$total=$row['total'];
$dis=3;
$total_page=ceil($total/$dis);
$page_cur=(isset($_GET['page']))?$_GET['page']:1;
$k=($page_cur-1)*$dis;
$q="select * from entries limit $k,$dis";
$ros=mysql_query($q,$link);
while($row=mysql_fetch_array($ros))
{
I've tried to change the line
$q="select count(*) \"total\" from entries";
to
$q="select count(*) \"total\" from entries id DESC";
however it does not seem to be working correctly.
Anyone has an idea how I can get this fixed and have the items sorted by ID?
Some expert help would be greatly appreciated - thank you very much.
Please find the original script I have in place here: http://allitstuff.com/php-mysql-pagination-script-download/

The coury
select count(*) \"total\" from entries
only returns the count. You can get only the total number of rows.
If you want to retrieve data please change your query.
If you want to manipulate with the count only, then try
$row=mysql_fetch_row($ros);
$total=$row[0];
Edit:
The OP want to sort the entries in a reverse order. So try
select column_name from entries order by column_name desc;

try it
$q="select count(*) as total from entries ORDER BY id DESC;";

Try this:
count(*) returns only count. FOR EXAMPLE
SELECT column_name1,column_name2,count(*)
FROM table_name
ORDER BY column_name1,column_name2 ASC|DESC;

Related

Select all values of one column, sorted by another column

I have a table stats with columns id, totalJumps, totalScore, topScore, and topScoreMod. I wish to select all id values and sort them by totalScore in descending fashion.
I have tried "SELECT id FROM stats ORDER BY totalScore DESC" but this gives me only one id result.
EDIT: My apologies, I have updated the question to be more accurate. This issue is likely with PHP, not with the SQL. The MySQLi query returns all 3 id values in the correct order, but the PHP statement $scoresRow = $scoresResult->fetch_array(), where $scoresResult is the above MySQLi query, returns an array with 2 values according to count($scoresRow), with $scoresRow[0] being 1 and $scoresRow[1] giving me the error Undefined offset: 1.
the query you have written is correct, it should show you all the id from your table on a desc order based on totalScore. may i know how many data you have on your table?
have you done, select * from stats order by totalscore desc? how many records shows up?
Have you tried using PDO extension? It ships with PHP and is the recommended library/extension to query the database. Follow instructions here
- http://php.net/manual/en/pdo.installation.php - to ensure that it's enabled.
Then you should be able to do something like this in PHP:
$stmt = $pdo->query("SELECT id FROM stats ORDER BY totalScore DESC");
while ($row = $stmt->fetch()) {
echo $row['id']."<br />\n";
}

selecting last element with sql select last and turing it into php variable

$sql="SELECT LAST(product_id) FROM producten";
$sql_result = $dbh -> query ($sql);
I want to select the last element from the column and turn in into a php variable called $product_id.
But I dont know how. Can anyone please tell me??
You can reverse order and take the first one
SELECT * FROM producten ORDER BY product_id DESC LIMIT 0,1

Adding an where clause breaks the query?

I have been trying to debug this for quite a while now with no success.
It seems that my mySQL query breaks as soon as I add a where clause to the below query.
Note this returns no results when it should:
SELECT * FROM `workorders` WHERE (`status`='Open') AND
`job_site_name` LIKE '%".$searchword."%' ORDER BY `date_promised` ASC LIMIT 20
This is the same query without the where clause and it returns results as expected, but I need the where status=Open as part of the query...
SELECT * FROM `workorders` WHERE
`job_site_name` LIKE '%".$searchword."%' ORDER BY `date_promised` ASC LIMIT 20
Furthermore, this works (and shows that the status column exists and works in other cases):
SELECT * FROM `workorders` WHERE (`status`='Open') AND `invoice_number` LIKE
'%".$searchword."%' ORDER BY `date_promised` ASC LIMIT 20
I appreciate any assistance in identifying the cause of this problem.
Many thanks in advance!
The issue seems to be both criteria are not met. If you need to use an OR clause then you can do
SELECT *
FROM `workorders`
WHERE (`status`='Open'
OR `job_site_name` LIKE '%".$searchword."%')
ORDER BY `date_promised` ASC
LIMIT 20

PHP & MySQL - Most efficient way to display last ten entries in a database?

So I have a database, and I would like to display the last ten entries.
So far I have tried several ways but run into a couple of issues. I have tried using a for-loop starting at the row count for the database and linking that to the ID, but then of course should I delete an entry the iterations will have data missing. For example if I have deleted lots of entries and have the first entry start at id 20 then if there are only 10 rows it will look to display 10 to 1, which don't exist.
Any thoughts?
You could try, depending on your implementation,
SELECT * FROM `table_name` WHERE conditions ORDER BY `id` DESC LIMIT 10;
Try this :
mysql_connect("localhost","usernm","pwd");
mysql_select_db("database");
$rs=mysql_query("SELECT id,col1,col2,coln FROM table_name WHERE condt ORDER BY id DESC LIMIT 10") or die(mysql_error());
while($row= mysql_fetch_row($rs))
{
print_r($row);
}

How do I query select all my mysql rows under the modification of a stored function with a reddit-based algorithm?

I've spent the whole day googling and deleting and inserting trying to implement this code. I've been trying to implement a reddit-like site using php and mysql. I have been following another question: PHP MYSQL Query Algorithm Help and it works very well and ranks rows according to the algorithm coded in the previous question within myphpadmin when I query a stored function
SELECT
*,
reddit_rank(`time_added`, `up_votes`, `down_votes`) as rank
FROM
`table`
ORDER BY
rank;
, but when I paste the query into my php file:
<?php
include("config.php");
$q= "SELECT *,reddit_rank(`time` , `votes_up` , `votes_down`) FROM `wallposts` ORDER BY rank LIMIT 0 , 30";
$r = mysql_query($q);
if(mysql_num_rows($r) > 0) {
while($row = mysql_fetch_assoc($r)){
...?>
It doesn't work and I get a white HTML screen. So for example in my PHP when I have
$q = "SELECT * FROM wallposts ORDER BY votes_up DESC";
my reddit/facebook-like wall has prepended each of my rows from mysql and everything works just fine. but when i change it to
$q= "SELECT *,reddit_rank(`time` , `votes_up` , `votes_down`) FROM `wallposts` ORDER BY rank LIMIT 0 , 30";
the webpage returns nothing but a white screen even though I know it works in myphpadmin.
Is there something wrong with my syntax or is it not possible to query a select all with a stored function to order the results in php?
I think I found a solution by creating a view and then querying that view instead of the original table. After I queried the stored function in myphpadmin:
SELECT
*,
reddit_rank(`time_added`, `up_votes`, `down_votes`) as rank
FROM
`table`
ORDER BY
rank;
I then created a view after those results were returned. Then instead of querying the same way in my PHP file, I queried the new mysql view with:
SELECT * FROM [view] ORDER BY rank
Voila!

Categories