Creating new PHP pages (pagination) I have a MySQL database, with a table called articles. There is a column in articles for its id, name, date_created, etc.

I want to create a page for each article, for example:


  example.com/article.php?id=1
  
  example.com/article.php?id=2
  
  ...


My code works right now, but is there anything I should do differently? I'm worried about the safety of the code. Is there a better way to validate/sanitize the id?

&lt;?php
        require_once('../mysqli_connect.php');




        if(isset($_GET['id'])){



            // Replace 
            $idv = preg_replace("#[^0-9]#","", $_GET['id']);


            $query = "SELECT name, description, date, id, date_created 
            FROM articles WHERE id = $idv LIMIT 1";

            $result = mysqli_query($dbc, $query);




            if ($result){

                $row = mysqli_fetch_assoc($result);


                if(!$row)
                {
                    //Row doesnt exist
                    //Redirect user somewhere else
                }
                else
                {
                    // echo blog post, with html
                }
            }



            else
            {
                echo "Couldn't issue database query &lt;br&gt;";  
                echo '&lt;p&gt;' . mysqli_error($dbc) . '&lt;/p&gt;';
                // Redirect user
            }



        }

        else
        {
            //Redirect user
        }




        mysqli_close($dbc);

    ?&gt;
In this case you just want your input to be an integer (or a long).
So using the regex is one idea.

But you should also consider malicious users. What if you try


  example.com/article.php?id=1000000000000000000000000000


Which is too big for int/bigint. When the exception is not caught well and your error pages expose information. Worst case this may expose information about the underlying directory structure. Which can be used by hackers while doing other attacks. And even when this is not the case, passing through exceptions are not a best practice.

I would rather use a built-in php method for that like intval. 

As an addition to this, you can also use prepared statements which is another very good way to protect against sql injections.

$idv = intval($_GET['id']);      
if($idv &gt; 0)
{
    $stmt = $mysqli-&gt;prepare("SELECT name, description, date, id, date_created FROM articles WHERE id = ? LIMIT 1");
    $stmt-&gt;bind_param("i", $idv);
    $stmt-&gt;execute();
    $stmt-&gt;bind_result($result);
    $stmt-&gt;fetch();
    $stmt-&gt;close();
}


ref: 


http://php.net/manual/en/function.intval.php
http://www.w3schools.com/php/php_mysql_prepared_statements.asp
https://phpbestpractices.org/