Danooned Danooned - 6 months ago 14
MySQL Question

Increase pages with PHP and SQL with $_GET[""]

Currently I am busy with a blog, but I get stuck at increasing pages, offset and limit. It is supposed to count up the page and show 10 rows at every page on button click. I have this:

<?php

$rowsPerPage = 10; //number of results you want to display
$num = $_GET["page"]; //set the offset to start w/the num. of results (good for paging)
$offset = ($num - 1) * $rowsPerPage; // to offset the limit count
$sql = "SELECT * FROM `posts` ORDER BY `id` DESC LIMIT ".$rowsPerPage." OFFSET ".$offset."";
$result = $conn->query($sql);
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo '<div class="post-preview">
<a href="posts.php?id='.$row["id"].'">
<h2 class="post-title">
'.$row["title"].'
</h2>
<h3 class="post-subtitle">
'.$row["content"].'
</h3>
</a>
<p class="post-meta"><a href="#">'.$row["creator"].'</a> | '.$row["date"].'</p>
</div>
<hr>';
}
?>


But it only seems to work with domain.com/index.php?page=1, it loads fine etc. When I remove the '/index.php?page=1' and go to the index without $_GET set I get the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-10' at line 1' in /home/u9778802/public_html/blog/index.php:49 Stack trace: #0 /home/u9778802/public_html/blog/index.php(49): PDO->query('SELECT * FROM `...') #1 {main} thrown in /home/u9778802/public_html/blog/index.php on line 49


I hope someone can help me.

Answer

While you're open to SQL injections, the logical issue can be fixed by using:

$num = (isset($_GET["page"]) and is_int($_GET["page"])) ? $_GET["page"] : 1;