I am using the below code to try and echo out the latest 5 entries on the MySQL table, I cannot, however seem able to figure how to limit the number of results, can anyone help me out by allowing me to limit the number of results to 5 rows?
<table>
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/resources/pdo.php");
$q = "SELECT * FROM `content` ORDER BY `id`";
$query = $pdo->query($q);
$data = array_reverse($query->fetchAll());
foreach ($data as $row) {
echo "<tr><td>{$row['title']}</td><td>{$row['id']}</td></tr>";
}
?>
</table>
Thanks!
Please note that I am new to PHP and I need help so if this question isn't useful, help me because I have only just started this.
Use LIMIT clause in your SQL query:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
From the manual:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
Use the LIMIT word:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
order by id desc to get rid of the array_reverse and limit 5 to cap the number of returned results.
$q = "SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5";
...
$data = $query->fetchAll();
As a global guideline: when writing queries try to formulate them in such a way that the resultset is as close to what you need as possible, ie no extra sorting or filtering operations afterwards.
having the dbserver send data that you aren't going to use is a waste
having to resort/refilter data on the webserver costs webserver performance and, in the case of big resultsets, it can cost lots of memory as well
When pulling data from a database you normally set a LIMIT via the MySQL-query, instead of counting the loop-iterations when reading the returned data.
$q = "SELECT * FROM `content` ORDER BY `id` LIMIT 5";
Related
Guys am trying to select the top/recently third row, i tried this one but it doesn't work, where do i make mistake ?
<?php
$sql = "SELECT * FROM songs ORDER BY id ASC LIMIT 1,2;";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['artist'];
}
}
?>
Use OFFSET:
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The shorthand (which you are using) is reversed, so OFFSET is first then LIMIT:
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1;
Use OFFSET
Here the limit 1 It simply means and you need one record
and the offset means skip the first 2
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The parameters you use after limit should be reversed.
The first parameter is offset, and the second parameter is number of record you want.
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1
This is just my opinion--
Sorting like this should always be done in client software.
Extract the data - remove the ORDER BY for your SQL...
Sort it in your client, and select and return the third line to the caller.
You will get better scalability and maintainability than driving all of this through an SQL query.
This is my go-to approach when solving these types of problems through custom software and it has been proven out over time.
Think about this:
Select ID from songs
get the id's into your code, and sort them there. Then chose the third one in the list. Then:
select title, author, artist, ... from songs where ID = VALUE FROM ID ABOVE
Yes, you are hitting the database twice, but these are two very efficient queries and that will perform better as your database scales, than the fancy order by you propose.
I'm trying to find a solution to select a list of rows coming after a certain Id from an ordered list.
For example, first I select 1000 rows. Then, on a subsequent request, i want to fetch another 1000 rows coming from after the last id of the first request. I know i can do it with limit, but suppose there has been 100 rows added between the first and second request, there will be 100 rows that will be from the first request.
Both queries will be ordered by the date of the entries.
Here's an example of the query I thought of:
$query = "SELECT * FROM table WHERE id AFTER $id ORDER BY date DESC";
$query = "SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT 1000";
Two ways to do this:
WHERE
"SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT $length"
LIMIT
"SELECT * FROM `table` LIMIT $start, $length"
$query = "SELECT * FROM table WHERE id > $id ORDER BY date LIMIT 1000";
You're asking about logic, not code so here it is.
The first request selects the first 1000.
$query = "SELECT * FROM the_table ORDER BY `date` DESC LIMIT 0,1000";
NB date is a reserved word so needs escaping if you've called a column "date" which you shouldn't.
$rs=$db->selectMany($query); // replace this with however you select the rows. $rs is results set
Do stuff with PHP and save the maximum id. They may not be in order.
$maxid=0;
foreach ($rs as $r){
// whatever you need to do with your results
$maxid=max($maxid, $r->id);
}
Your subsequent select uses the last id
$query = "SELECT * FROM the_table WHERE id > $maxid ORDER BY date DESC LIMIT 0,1000";
BUT you need to take note that you're ordering by date and using id to find a breakpoint which sounds like it would cause data to be missed.
Perhaps you mean to use WHERE`date`> $maxdate? If so you can figure that out from the code given.
I'm trying to limit the array mysql_fetch_assoc($query), and am unsure on how I would go about it.
$query = mysql_query('SELECT * FROM table ORDER BY id DESC');
while($output = mysql_fetch_assoc($query))
{
//do something
}
Do you add a counter or something? How do you add this counter?
I'm really confused about mysql_query and mysql_fetch_assoc. Please Help!
After your ORDER BY id DESC, add LIMIT 100 (or whatever number you want). For the next 100 rows, use LIMIT 100,100, then LIMIT 200,100 and so on.
You can limit the results directly in the SQL query. To get the top 100 records do
SELECT * FROM table
ORDER BY id DESC
LIMIT 100
Use LIMIT
SELECT * FROM table ORDER BY `id` DESC LIMIT 10;
Haven't you seen phpMyAdmin always limiting to 30?
I have a table as below,
ID Name Age
----------------------
100 A 10
203 B 20
Now how do i select only row1 using MySQL SELECT command and then I've to increase +1 to it to select row2. In short I'll be using for loop to do certain operations.
Thanks.
Sounds like you've got a mix up. You want to select all the rows you want to iterate through in your for loop with your query, and then iterate through them one by one using php's mysql functions like mysql_fetch_row
You should not try to use tables in a linear fashion like this. Set your criteria, sorting as appropriate, and then to select the next row use your existing criteria and limit it to one row.
SELECT * FROM `table` ORDER BY `ID` LIMIT 1
SELECT * FROM `table` ORDER BY `ID` WHERE ID > 100 LIMIT 1
You'd probably be better off retrieving all rows that you need, then using this. Note the LIMIT is entirely optional.
$query = mysql_query(' SELECT ID, Name, Age FROM table_name WHERE condition LIMIT max_number_you_want '))
while ($row = mysql_fetch_assoc($query)
{
// Do stuff
// $row['ID'], $row['Name'], $row['Age']
}
Lots of small queries to the database will execute much slower than one decent-sized one.
You should get the result into an array (php.net : mysql_fetch_*).
And after you'll can loop on the array "to do certain operations"
Yep, this is a pretty common thing to do in PHP. Like the others who have posted, here is my version (using objects instead of arrays):
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_object($result)) {
// Results are now in the $row variable.
// ex: $row->ID, $row->Name, $row->Age
}
If I have a PHP function that generates a random number, is it possible to pass that variable into the sql statement in the WHERE clause? I'm using CodeIgniter, so this is my code using its syntax.
$random = rand(1, 572);
$result = $this->db->query( ' SELECT part1, part2, _id FROM `questions` WHERE `_id` >= '$random' LIMIT 0,1 ');
Is this even possible to do?
EDIT: The reason I want the php to execute the random number is because I need to call it multiple times throughout my pages, and it needs to do another call to another database using a sql query
Yes it is possible if you concatenate the variable with the string:
$query = "SELECT
part1,
part2,
_id
FROM
questions
WHERE _id >= " . $random . " LIMIT 0,1";
$result = $this->db->query($query);
But if what you want is to select a random row, then you might want this query
SELECT part1, part2, _id FROM questions ORDER BY RAND() LIMIT 1
EDIT
I understand that _id will be random, but you are specifying the min and max for rand(), right? So you'd have to change it whenever you insert a new row, or you'd have to use two queries if you want to make sure rand() does not return a value too high. By using ORDER BY RAND() you are free from both problems. You simply have to get the value of _id that was returned from the query.
This might just be a mater of using double quotes instead of single quotes on the outside of your string.
$result = $this->db->query("SELECT part1, part2, _id FROM `questions` WHERE `_id` >= '$random' LIMIT 0,1 ");
Try this:
$result = $this->db->query("SELECT part1, part2, _id FROM questions WHERE _id >= '".$random."' LIMIT 0,1 ");