Question:
Only query last mysql record?
Deception
2013-04-17 13:27:45 UTC
I have a php script and I want it to only query the last 3 records:

At the moment it query's all the records:

$query = "SELECT postbody, postdate FROM posts ORDER BY id DESC";
$result = mysql_query($query);

How would I make it so that it only query's the last 3 records.

Thanks!
Three answers:
sparky_dy
2013-04-17 13:40:45 UTC
Use the LIMIT modifier. Change your query to



$query = "SELECT postbody, postdate FROM posts ORDER BY id DESC LIMIT 3";



Or (but this probably is less efficient) use a variable to keep track in your PHP script of how many records you have retrieved already, and just stop calling mysql_fetch_array after retrieving 3 records. You probably will only notice any performance degradation if you have a really popular website that gets many concurrent hits.



BTW they may not have mentioned it in your textbook, but you can do something like this:



list($postbody, $postdate) = mysql_fetch_array($result, MYSQL_NUM);



to assign the query results straight into scalar variables, without needing to access them through an associative array.
raina_vissora
2013-04-17 20:30:49 UTC
Add "LIMIT 3" to the query.
AɾṡεRαρτøɾ
2013-04-17 20:28:37 UTC
You won't get the job, because you're an autistic retarded manchild.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...