I’ve had a really hard time understanding even the “simple” pagination tutorials on the internet.
I am in the process of creating an Intranet site for my company and the only step in order to complete it is to paginate all of the queries as they would all contain thousands of results, especially search results.
My question is would I be able to paginate a query the way it is below:
SELECT * FROM hdticket WHERE id = 22;
You need to add a
LIMITclause to your MySQL query. This is as simple as:This will fetch ten records, starting from the beginning (imagining your records are zero index–based). The first number is when to start fetching from, and the second number is how many thereafter to fetch. So from 0, it’s fetching the next ten records. This would be page 1.
To get subsequent pages of records, you only need to increment the first number. So, to get page two, you would need to start counting from 10, and fetch the next 10 records. This query would look like this:
And then page 3:
And so on. Hopefully you can see the pattern emerging.
As you’re using
$_GETparameters, you could then just tailor your URLs to page your records. So a URL of http://intranet/index.php?page=2 would give:Hope this helps.
Also, a couple of asides. Don’t use the
mysql_functions as they’re deprecated. You can see this from the official manual page: http://php.net/manual/en/function.mysql-query.php.Furthermore, your code is vulnerable to SQL injection attacks, because you’re taking what’s in the URL and using it in the SQL query directly. This is all good and well if you’re putting numbers for pagination in there, but if someone nefarious puts SQL in the URL, they can do all sorts of things such as truncating your tables or your entire database, and it will happen because you’re just passing it through without checking it.
To combat this, you can prepare variables in SQL statements if you use an alternative to the
mysql_functions, like PDO. Your code would look something like this:This ensures that the data passed to your SQL string is what you expect, and automatically escaped to prevent SQL injection.