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
Related
I thought this would be simple but I'm having a tough time figuring out why this won't populate the the data array.
This simple query works fine:
$queryPrice = "SELECT price FROM price_chart ORDER BY id ASC LIMIT 50";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
But instead I want it to choose the last 10 results in Ascending order. I found on other SO questions to use a subquery but every example I try gives no output and no error ??
Tried the below, DOESN'T WORK:
$queryPrice = "SELECT * FROM (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
I also tried specifying the table name again and using the IN, also doesn't work:
$queryPrice = "SELECT price FROM price_chart IN (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
In both examples my array is blank instead of returning the last 10 results and there are no errors, so I must be doing the subquery wrong and it is returning 0 rows.
The subquery doesn't select the id column, so you can't order by it in the outer query. Also, MySQL requires that you assign an alias when you use a subquery in a FROM or JOIN clause.
$queryPrice = "SELECT *
FROM (SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) x ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice) or die (mysqli_error($conn));
$data = array();
while ($row = mysqli_fetch_assoc($resultPrice)) {
$data[] = $row['price'];
}
You would have been notified of these errors if you called mysqli_error() when the query fails.
Your second query is the closest. However you need a table alias. (You would have seen this if you were kicking out errors in your sql. Note you will need to add any field that you wish to order by in your subquery. In this case it is id.
Try this:
SELECT * FROM (SELECT price, id
FROM price_chart ORDER BY id DESC LIMIT 10) as prices
ORDER BY id ASC
You must have errors, because your SQL queries are in fact incorrect.
First, how to tell you have errors:
$resultPrice = mysqli_query (whatever);
if ( !$resultprice ) echo mysqli_error($conn);
Second: subqueries in MySQL need aliases. So you need this:
SELECT * FROM (
SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) AS a
ORDER BY id ASC";
See the ) AS a? That's the table alias.
I am trying to display questions, along with the users answer in a specific order, NOT ASC or DESC, but as defined by the "question_order" column.
I have the following tables in a mysql db:
questions (qid, question_text)
answers (aid, uid, answer)
usermeta (userid, question_order)
"questions" table contains the questions
"answers" table contains every users answers to all questions
"usermeta" table contains the sort order for the questions in "question_order".
"question_order" is unique per user and is in the db as a pipe delimited list. (i.e.: 85|41|58|67|21|8|91|62,etc.)
PHP Version 5.3.27
If this entire procedure can be better accomplished using a completely different method, then please let me know.
My PHP ability is limited. With that said, below is what I have at the moment after several hours of playing ...
$sql = "
SELECT
*
FROM
".USERMETA_TABLE."
WHERE
userid = {$userid}
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row = $result->fetch_assoc();
$order_array = explode('|', $row['question_order']);
$sql = "
SELECT
*
FROM
".QUESTIONS_TABLE."
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row = $result->fetch_assoc();
// my attempt at sorting the questions. the $order_array
// does not have a unique id so I am kind of lost as to
// how to make this work
usort($myArray, function($order_array, $row) {
return $order_array - $row['qid'];
});
$sql = "
SELECT
*
FROM
".QUESTIONS_TABLE."
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
while ( $row = $result->fetch_assoc() )
{
$sql = "
SELECT
*
FROM
".ANSWERS_TABLE."
WHERE
uid = {$userid}
AND
qid = ".$row['qid']."
LIMIT
1
";
$result2 = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row2 = $result2->fetch_assoc();
echo ' <p>'.$row['question_text'].'</p>'."\n";
echo ' <p>'.$row2['answer'].'</p>'."\n";
}
Filter out the data when retrieving from db.
Use:- SELECT * FROM [TABLE_NAME] ORDER BY qid DESC
Then in PHP you can use session variables and modify the values accordingly.
If you want to order using ID you can use
SELECT * FROM [TABLE_NAME] ORDER BY qid DESC
this will order in descending order If you want in ascending order use ASC
I went ahead and altered the DB by adding a table to store the question numbers, user sort order, and student user id:
student_id, sort_order, question_id
1 1 8
1 2 2
1 3 97
and then was able to select it all with the following statement:
SELECT q.*
FROM
questions q
JOIN questions_sorting_order qso
ON q.id = qso.question_id
ORDER BY qso.sort_order
WHERE qso.student_id = $student_id
...works great.
Thanks to FuzzyTree for his help on this at: How do I sort data from a mysql db according to a unique and predetermined order, NOT asc or desc
I have the following MySQL table:
table_1
id | value_1 | value_2 | value_3
1 hehe haha stack
2 over flow me
3 123 abc hello
4 hi random php
5 html js css
How can I select value_2 from 3rd row, which is "abc"?
Something like $rows[3]['value_2']
Here's the code I had tried with:
$sql=mysql_query("SELECT * FROM table_1 ORDER BY `table_1`.`id` ASC");
$rows=mysql_fetch_array($sql);
//And then I tried accessing it by "$rows[3]['value_2']" and $rows['value_2'][3]
I can't use SELECT * FROM table_1 WHERE id='3', because I need to access multiple lines (all of them). I can't use a WHILE loop also, because I need the values in very different places in the code.
mysql_fetch_array only returns a row corresponding to the query. The proper use of mysql_fetch_array is as such:
$sql=mysql_query("SELECT * FROM table_1 ORDER BY `table_1`.`id` ASC");
while ($row = mysql_fetch_array($sql)) {
printf("ID: %s value_2: %s", $row[0], $row[2]);
}
http://www.php.net/manual/en/function.mysql-fetch-array.php
Found the answer. You can now access them how you wanted.
$sql=mysql_query("SELECT * FROM settings ORDER BY `settings`.`id` ASC");
$id=0;
while ($rows = mysql_fetch_array($sql)) {
$settings[$id]['value_1']=$rows['value_1'];
$settings[$id]['value_2']=$rows['value_2'];
$settings[$id]['value_3']=$rows['value_3'];
$id++;
}
echo $settings[5]['value_3'];
echo $settings[5]['value_1'];
echo $settings[4]['value_2'];
echo $settings[0]['value_3'];
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>";
}
?>
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>";
}