Okay, so i want this code snippet to check if variable $_GET['p'] exists in the DB, if it does then make $p = $_GET['p'], if it doesn't exist then make $p = '1', and if $_GET['p'] isn't even set in the link then just display page with id of 0 ($p = '0';). Here is my code. It only shows the "unknown page" when variable is set in the link.
if (isset($_GET['p']))
{
$getpage = $_GET['p'];
$sql = sprintf("SELECT * FROM pages WHERE id=%d LIMIT 1", $getpage);
$result = $con->query($sql);
if ($result && $result->mum_rows > 0 ){
// if page id exists in "pages" table, then make $p = $_GET['p'].
$p = $getpage;
}
else
{
// if "p" ID doesn't exist in DB, then show "unknown page" page with id of "1".
$p = '1';
}
}
else if (!isset ($_GET['p']))
{
//if variable "p" isn't set in link then display homepage or page with ID of 0.
$p = '0';
}
As I commented it's merely about code-formatting and arrangement, here another suggestion that helps a lot when you're doing trouble shooting and is very simple to do:
function has_page_row(Mysqli $db, $pageId)
{
$sql = sprintf("SELECT * FROM pages WHERE id=%d LIMIT 1", $getpage);
$result = $db->query($sql);
return $result && $result->mum_rows > 0;
}
$hasGet = isset($_GET['p']);
$hasRow = $hasGet && has_page_row($con, $_GET['p']);
$p = '0';
if ($hasRow) {
$p = $_GET['p'];
} elseif ($hasGet) {
$p = '1';
}
You can then also easily fix the issue about the dorky SQL query by changing the code inside the new has_page_row
function, see: