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
?
<?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 <br>";
echo '<p>' . mysqli_error($dbc) . '</p>';
// Redirect user
}
}
else
{
//Redirect user
}
mysqli_close($dbc);
?>
//...
s in your code that are in places where it seems like code would be. Have you included all the code that you would live reviewed? \$\endgroup\$ – SirPython Oct 25 '15 at 1:20