Mysql ORDER BY numbers DESC - php

I have a simple mysql select query in my PHP code:
$result = mysql_query("SELECT text FROM example ORDER BY rank DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] . "<br>";
}
and this MySql table:
text | rank
--------+--------
google | 245
--------+--------
yahoo | 32
--------+--------
bing | 12
When I get the results from the query, something like this gets displayed:
yahoo
google
bing
I want Google to be in front. I guess Yahoo is in first because it starts with "3".
How could I make the query order the results by the size of the numbers in rank?
Thanks...

I'm guessing the rank field is some kind of string type. Make it a numeric type int and it will order properly

The correct solution, of course, is to use the correct data type. As a workaround you could cast the data to number on the fly:
SELECT text FROM example ORDER BY rank + 0 DESC
or:
SELECT text FROM example ORDER BY cast(rank as unsigned) DESC

What's the data type of rank in your SQL schema? Set it to a numeric type.

Try this:
$result = mysql_query("SELECT * FROM example ORDER BY rank DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] . " ". $row['rank'] ."<br>";
}
And see if the ranks are being sorted correctly.

$result = mysql_query("SELECT * FROM `example` ORDER BY `rank` DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] ."<br>";
}

Related

Issue with rand() function in PHP

I'm having a little trouble with my rand() function. I have the following query:
$listTrainers = mysqli_query($conn, "SELECT emp_id FROM employees;");
while($fetchTrainers = mysqli_fetch_row($listTrainers))
{
echo 'ID: ' . $fetchTrainers['0']. '<br>';
}
This query returns me the id of all employees in the database, is there a way I can randomly select one of these id's and store it in a variable?
I am trying to use the following function:
echo(rand(begin, end));
where begin is the first element from the query and end is the last element
add this to your query:
ORDER BY RAND() LIMIT 1
You can do so within your query easily
SELECT emp_id FROM employees ORDER BY RAND() LIMIT 1
The easiest way is to do this directly in the database, to avoid getting all IDs if you only need one:
SELECT
emp_id
FROM
employees
ORDER BY
RAND()
LIMIT
1
If you do need all IDs, but additionally want to pick a random one, use this to avoid querying the database twice:
$listTrainers = mysqli_query($conn, "SELECT emp_id FROM employees;");
while($fetchTrainers = mysqli_fetch_row($listTrainers))
{
$id = $fetchTrainers[0];
echo 'ID: ' . $id . '<br>';
$ids[] = $id;
}
$randomId = $ids[array_rand($ids)];

SQL LEFT JOIN without duplicating same row values

I was wondering if someone can help me with my problem that is as follows:
I want to pull once posts.text and uids which belongs to that posts.text but when I execute the code below it does this: eg. there are 4 uids that belongs to the post so I get the posts.text four times instead of once.
$query = mysqli_query($con,
"SELECT posts.text, relationships.uidb
FROM posts
LEFT JOIN relationships
ON posts.uid=relationships.uida
LIMIT 10");
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
echo $row['text']." ".$row['uidb']."<br>";
}
}
I would really appreciate any help.
Thanks is advance.
Peter
Update:
Desired output would be like this:
postsArray[0]->text = //post text
postsArray[1]->text = //another post text
postsArray[0]->uids[0] = //approved uid for first post
postsArray[0]->uids[1] = //another approved uid for first post
now it outputs this:
text 10
text 15
text 12
and I want this:
text 10, 15, 12
One way is to use Mysql's GROUP_CONCAT which provides comma separated values list for each group i.e (p.uid)
$query = mysqli_query($con,
"SELECT p.text, GROUP_CONCAT(r.uidb SEPARATOR ', ') uidbs
FROM posts p
LEFT JOIN relationships r
ON p.uid=r.uida
GROUP BY p.uid
LIMIT 10");
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_assoc($query)) {
echo $row['text'].' '.$row['uidbs'];
/*$uidbs= explode($row['uidbs'],',');
foreach ($uidbs as $key => $val) {
echo $val.' ';
}*/
echo '</br>';
}
}
GROUP_CONCAT
According to docs The result is truncated to the maximum length that
is given by the group_concat_max_len system variable, which has a
default value of 1024. The value can be set higher, although the
effective maximum length of the return value is constrained by the
value of max_allowed_packet.
Maybe this might work for you:
$query = mysqli_query($con,
"SELECT posts.text, relationships.uidb
FROM posts
LEFT JOIN relationships
ON posts.uid=relationships.uida
GROUP BY posts.uid
LIMIT 10");
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
echo $row['text']." ".$row['uidb']."<br>";
}
}
SELECT posts.text, relationships.uidb
FROM posts
LEFT JOIN relationships
ON posts.uid=relationships.uida
GROUP BY posts.primary_key_of_your_post
LIMIT 10
You should call 2 queries. In your first query, call the text, and then call uids.
You should not write complex queries because this will make your business more complex and you will not maintain your code in future.

php database table select limited

im new on php programming and i've searched the function that i need but didn't found it.
here what exactly i want to do :
i want to select 2 columns from a table
set the order by descending by 1 column that is numeric
and then show in php the first 100 rows that were selected
Here is my code right now php shows all the columns i want it to show the first 100
$result = mysqli_query($con,"SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC");
while($row = mysqli_fetch_array($result))
{
echo $row['pvpkills'] . "&nbsp " . $row['char_name'];
echo "<br>";
}
SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC LIMIT 0,100

PHP MySQL query outputs only a two-element array

I just made a quick little script with SQL query.
Now when I go to phpmyadmin and execute
SELECT name FROM players WHERE online='1' ORDER BY name ASC
It outputs the desired players ( 0TheMonk, Player, Veeve )
But with PHP:
$query=mysql_query("SELECT name FROM players WHERE online='1' ORDER BY name ASC");
$query_array=mysql_fetch_array($query);
echo implode(',',$query_array);
It echoes: 0TheMonk,0TheMonk
Instead of: 0TheMonk,Player,Veeve
It always outputs the first player in the array, twice. What am I doing wrong?
Thanks in advance.
Use while loop
$query=mysql_query("SELECT name FROM players WHERE online='1' ORDER BY name ASC");
while($query_array=mysql_fetch_array($query))
{
echo $query_array['name'].",";
}
Try this : Almost same as Sumits answer.
$res = array();
$query=mysql_query("SELECT name FROM players WHERE online='1' ORDER BY name ASC");
while($query_array=mysql_fetch_array($query))
{
$res[] = $query_array['name'];
}
echo implode(",",$res);
In this case there will not a extra , at the ens

SELECT * FROM table_name ORDER BY column_name?

ok so i coded in a news section and everytime i insert new news,its shows below the old one.
i want to make it ORDER BY id but make it start like backwards.i dont know how to explain but yeh
i want them to be ordered by the newest added by the id so if the 1st row that was inserted's id is 1 then i want it to show below the next id.
so row with id = 2 will be here
so row with id = 1 will be here
thats how i want it to be, instead of it being like this
so row with id = 1 will be here
so row with id = 2 will be here
.
Sorry for my bad explanation i hope this is understandable
heres my code so far
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id");
while($row = mysql_fetch_array($sqlnews)) {
$dbdate = $row['date'];
$dbnews = $row['news'];
echo "<h1><strong>$dbdate</strong></h1>";
echo "<div class='content'>$dbnews</div><br><br>";
}
?>
add DESC in your ORDER BY clause
SELECT * FROM news ORDER BY id DESC
by default, it is in ASC mode.
SELECT * FROM news ORDER BY id DESC
DESC is the descending keyword ASC is ascending
If you specify neither then default behaviour is ascending
Just use DESC keyword in your sql query.
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
However, it isn't really such a good idea to use id, because semantically, there is nothing preventing somebody from changing the sequence which counts up automatically assigning the ID.
Therefore, you should add a column created_at. Everytime you insert a row, you can use the SQL function NOW().
The advantage is that you can say:
SELECT * FROM news WHERE created_at <= NOW() ORDER BY created_at DESC
This means that you can schedule news items ahead of time, and it will automatically display when the date/time arrives!
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
try this:
just have to add
order by id DESC
Just replace your code by this code:
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
while($row = mysql_fetch_array($sqlnews)) {
$dbdate = $row['date'];
$dbnews = $row['news'];
echo "<h1><strong>$dbdate</strong></h1>";
echo "<div class='content'>$dbnews</div><br><br>";
}
?>

Categories