Is this php select statement secure?

83 views Asked by At

I'm parsing a url and using the number as an id to pull out the specific entry

So with a statement such as:

$blog_id = 5;

$query = "SELECT id,entry,date,views,comments,likes FROM blogs WHERE id=$blog_id ORDER by Id DESC";

Is that secure or should I use ....id=?... and use a bind_param ?

5

There are 5 answers

3
Realitätsverlust On BEST ANSWER

Actually: This code is secure. Why? It doesn't take any user input. So there is nothing to modify.

While this doesn't make sense, there is no way to perform an SQL Injection here. Once you are using POST, GET or Cookies, you HAVE TO validate the incoming information. You can do this by using PDO::bind_param, filter_var() or htmlspecialchars()

1
Tobi On

You should use prepared statement for your sql, because you insert some values from an url, which can be manipulated and destroy your database

0
kojow7 On

Your code shows that you are not getting the value from a URL but are hardcoding the value 5 into the variable with

$blog_id = 5;

If instead you have something like this

$blog_id = $_GET['blogid'];

then your code is insecure and open to MySQL injection. In that case you should use prepared statements which can include ? and bindParam. You can either use mysqli or PDO to do this. I prefer PDO.

3
seb-o-matic On

That seems vulnerable to SQL Injection. You have to check that $id only contains characters that are valid for your ids, and that is doesn't have semicolons or SQL Keywords

1
Matts On

If the variable $blog_id can't be changed (as shown in your question), you could say that this is safe. Yet it is recommended to always use prepared statements to prevent sql injection.

More info can be found at http://php.net/manual/en/pdo.prepared-statements.php