-1

Here is URL:

http://ex.com/members.php?id=5320

Here is code:

mysqli_query("SELECT * from members where id='$_GET[id]'");

which method is secure?

  • 1
    Don't ever use `$_GET` directly in a query. You firstly have to sanitize it. – fedorqui Mar 22 '14 at 12:08
  • If you're using MySQLi (as you appear to be) then use prepared statements with bind variables – Mark Baker Mar 22 '14 at 12:09
  • You can try `WHERE id = " . mysql_real_escape_string($_GET["id"])` but `mysqli_*` functions with [**prepared statements**](http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) or [**PDO**](http://php.net/pdo) is better. – Funk Forty Niner Mar 22 '14 at 12:10
  • Use [_Prepared Statements_](http://php.net/manual/en/mysqli.prepare.php) on MySQLi and you don't have to worry about injections. – Shankar Narayana Damodaran Mar 22 '14 at 12:12
  • possible duplicate of [How can I prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Gumbo Mar 22 '14 at 12:16
  • You can use prepared statements with either MySQLi or with PDO; I've added a link to my answer that shows how to secure queries with both extensions – Mark Baker Mar 22 '14 at 12:18
  • http://www.phptherightway.com/#databases – Mark Baker Mar 22 '14 at 12:25

1 Answers1

2

Use prepared statements and bind variables when you're using MySQLi

$stmt = $mysqli->prepare("SELECT * from members where id=?");
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();

You may also wish to validate that $_GET['id'] is an integer first, and return an error message if it isn't rather than have all the overhead of a db query to return nothing.

Read this answer to a previous question to understand why yu should take this approach

Community
  • 1
  • 1
Mark Baker
  • 209,507
  • 32
  • 346
  • 385