ORDER BY id DESC - php

I simply want to ORDER the comments by the ID, but I have no luck in doing it. Can't figure out what to do, because this is confusing me: articleid='" . mysql_real_escape_string($_GET['id']) . "'
Would you guys happen to know how I could go about ordering the comments by the id in DESC? thanks!
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'"); $comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'");
if (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
while($row = mysql_fetch_array($grab)){
?>

First of all you're doing the same SELECT two times. That's pretty unnecessary since you can count rows and get the data from a single query. Additionally to this replace commentid with the unique id of your comment table and you're set. Replace DESC with ASC to reverse the sort order.
<?php
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY commentid DESC");
$comments = mysql_num_rows($grab);
if (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
while($row = mysql_fetch_array($grab)){
?>

add ORDER BY clause
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY articleid, ID DESC");
your query is vulnerable with SQL Injection, please read the article below to protect from it,
How can I prevent SQL injection in PHP?

try this
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' order by articleid desc");

I think your comments table habe a column id then, so:
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY id DESC");
This is a sql thing to sort it, not php, so you just have to modify your sql statement.

$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY id DESC ");
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY id DESC");

Three suggestions:
1) Complete your "select" statement in a string variable (as shown below; it makes debugging much easier)
2) Consider using prepared statements instead of raw "select" (or update or delete!).
It can help performance. But it makes your PHP much more secure!
3) Consider moving away from the (deprecated) mysql_query() syntax
<?php
$sql =
"SELECT * FROM comment WHERE articleid='" .
mysql_real_escape_string($_GET['id']) . "' order by articleid desc";
$amount_get = mysql_query($sql);
$comments = mysql_num_rows($amount_get);
$sql =
"SELECT * FROM comment WHERE articleid='" .
mysql_real_escape_string($_GET['id']) . "'order by articleid desc";
$grab = mysql_query($sql);
...
Here's a good link on the mySQLi and PDI APIs that supercede the old mysql_query() syntax:
mysqli or PDO - what are the pros and cons?
And here's a good link on prepared statements:
http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/#axzz2Dazi7pQ4

You can use order by clause in your query
<?php
$getarticles = array();
$getarticles = mysql_query("SELECT * FROM comment order by articleid desc");
if(empty($getarticles)){
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
echo "<pre>";
print_r($getarticles);
echo "</pre>";
for($i=0;$i<count($getarticles);$i++){
//display
}
?>

Related

How to use multiple where conditions PHP SQL

I am trying to create a query using multiple WHERE conditions, both AND and NOT, and I am having trouble. Both conditions work separately, but not together. Most likely I've gotten the syntax wrong.
Here's the query
$getposts = mysql_query("SELECT * FROM Posts WHERE (category=".$_POST['category'].") AND (id NOT IN ( '" . implode($array, "', '") . "' )) ORDER BY popularity DESC") or die(mysql_query());
I've tried with and without parentheses, but with no change. As I say, both this query:
$getposts = mysql_query("SELECT * FROM Posts WHERE category=".$_POST['category']." ORDER BY popularity DESC") or die(mysql_query());
and this query:
$getposts = mysql_query("SELECT * FROM Posts WHERE id NOT IN ( '" . implode($array, "', '") . "' ) ORDER BY popularity DESC") or die(mysql_query());
work, just not when combined.
Any help is much appreciated!

MySQL does not retrieve first item in PHP

I've now been trying for hour and can't figure the problem out. I've made a php file that fetch all items in a table and retrieves that as JSON. But for some reason after I inserted the second mysql-query, it stopped fetching the first item. My code is following:
...
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
$row2 = $result2->fetch_assoc();
while($row = $result2->fetch_assoc()) {
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,
strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
Any help is greatly appreciated.
EDIT: Thanks for all those super fast responses.
First you're fetching a row:
$row2 = $result2->fetch_assoc();
Then you start looping at the next row:
while($row = $result2->fetch_assoc()) {
If you want to loop over all of the rows, don't skip the first one. Just loop over all of the rows:
$result2 = // your very SQL-injectable query
while($row2 = $result2->fetch_assoc()) {
$result3 = // your other very SQL-injectable query
$row3 = $result3->fetch_assoc();
// etc.
}
Note that errors like this would be a lot more obvious if you used meaningful variable names. "row2", "result3", etc. are pretty confusing when you have overlapping levels of abstraction.
Important: Your code is wide open to SQL injection attacks. You're basically allowing users to execute any code they want on your database. Please look into using prepared statements and treating user input as values rather than as executable code. This is a good place to start reading, as is this.
No Need of $row2 = $result2->fetch_assoc();
<?
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
while($row = $result2->fetch_assoc())
{
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
?>
Or,
<?
...
case "LoadEntryList":
$Category=$_POST["Category"];
$Offset=$_POST["Offset"];
$Quantity=$_POST["Quantity"];
$result3 = performquery("SELECT Entries.*, Users.Username FROM Entries, Users WHERE Entries.Category=$Category AND Entries.UserID=Users.ID LIMIT $Offset, $Quantity");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
?>
I have a addition to David answer(can't comment on it yet)
This line of code:
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
will always return with the same result. If you were to change $row2[... into $row[... the code would take the rows that get updated by the while loop.
I am not content with the accepted result. The snippet can be fixed / replaced, and also a bad code must be replaced. Also not to mention is that I don't know if anyone spotted a really big mistake in the output. Here is the fix and I'll explain why.
$JSON = array();
$result2 = performquery( '
SELECT
e.*, u.Username
FROM Entries AS e
LEFT JOIN Users AS u ON u.ID = e.UserID
WHERE
e.Category = ' . $_POST['Category'] . '
LIMIT ' . $_POST['Offset'] . ', ' . $_POST['Quantity'] . '
' );
while( $row2 = $result2->fetch_assoc() ){
$JSON[] = $row2;
}
echo json_encode( $JSON );
Obviously the main issue is the query, so I fixed it with a LEFT JOIN, now the second part is the output. First it's the way you include the username, and the second what if you had multiple results? Than your output will be:
{"ID":1,"Username":"John"}{"ID":2,"Username":"Doe"}
How do you parse it? So the $JSON part comes in place. You add it to an array and will encode that array. Now the result is:
{["ID":1,"Username":"John"],["ID":2,"Username":"Doe"]}
LE: I left out the sql inject part which as stated by the OP, will be done afterwards? I'm not sure why not do it at the point of writing it, because you may forget later on that you need to sanitize it.

Printing table values in ascending order

I am trying to print out a users name and totalspent value in ascending order of totalspent. I.e, user that has spent the most will be outputed first then the next highest spender etc.
This is my current code, however, this only seems to output a single table row an infinite amount of times.
$query = "SELECT * FROM (
SELECT * FROM `members` ORDER BY `totalspent` DESC LIMIT 10) tmp order by tmp.totalspent asc";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
select member_name, totalspent from tmp order by totalspent desc;
still can you show snippet of your table and snippet of answer you desire
The best way I can prefer for you to join two tables. The code should like follows-
$query = "SELECT * FROM temp.tmp, mem.members WHERE temp.totalspend = mem.totalspend ORDER by temp.totalspend ASC";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
I believe, it will work for your smoothly... TQ

jQuery and php. mysql error

My code loads with the following text on top of it:
"Problem with SQL: SELECT * FROM table WHERE id < ORDER BY id DESC LIMIT 5"
Could someone help me find a solution?
Thanks
//jQuery
var value = '3';
$.post("load.php", {number: value} ,function(data){
$('p').append(data);
});
$('p').load('load.php');
//PHP load.php
//I have the escape inside $db.
$random = $_POST['number'];
$db->query('SELECT * FROM table WHERE id <' . '$random' . 'ORDER BY id DESC LIMIT 1');
$result = $db->get();
foreach ($result as $key => $value){
echo $value['user'];
};
//Output
Problem with SQL: SELECT * FROM table WHERE id < ORDER BY id DESC LIMIT 5
$value['user']
Try changing it to this one:
$db->query("SELECT * FROM table WHERE id < " . $random . " ORDER BY id DESC LIMIT 1");
Better use double instead of single quotes.
The reason this is not working is because single quotes does not allow PHP to expand the variable value.
So instead of this:
$db->query('SELECT * FROM table WHERE id <' . '$random' . 'ORDER BY id DESC LIMIT 1');
You might do this:
$db->query('SELECT * FROM table WHERE id <' . $random . ' ORDER BY id DESC LIMIT 1');
Just remove the quotes in $random and you'll be well.

MySQL - Select differently

I have this query, which selects a distinct value for a column, but I need something else in that query too. I need it to fetch a different row associated with the main select.
Let me illustrate...
This is my query:
$sql = 'SELECT DISTINCT user_id FROM ' . DONATION_SECURITY_TABLE;
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
mysql_free_result($result);
return $rows;
As you see it returns this query returns the DISTINCT of user_id.
If I use a function like this in a double foreach loop created using the return of the query above:
public function get_donor_status($user_id)
{
global $db;
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$payment_status = $row['payment_status'];
$db->sql_freeresult($result);
return $payment_status;
}
This function would return Completed for user_id 2, but I want it to say Pending instead. How would I change my query so it returns the last value for the corresponding user_id?
If I'm not clear enough, please let me know so I can reexplain.
Just select the last row for the user:
"SELECT payment_status FROM " . DONATION_SECURITY_TABLE . " WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1"
How about this?
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1";
You can actually get everything in one SQL statement, no need for a double loop:
SELECT
user_id, payment_status
FROM
DONATION_SECURITY_TABLE t1
WHERE
donation_id = (select max(donation_id) from DONATION_SECURITY_TABLE t2 WHERE t2.user_id = t1.user_id)
ORDER BY
user_id

Categories