What is wrong with this SQL query?

6 replies
Hi Warriors,

Can you please explain in simple terms why this query is wrong?

SELECT * FROM table WHERE id = $_GET['id']

Thanks!

Bret
#query #sql #wrong
  • Profile picture of the author Cosmit
    Originally Posted by GowebMkt View Post

    Hi Warriors,

    Can you please explain in simple terms why this query is wrong?

    SELECT * FROM table WHERE id =

    Thanks!

    Bret
    1. "Table" is a special term. Escape table name with `quotes`
    2. $_GET['id'] is not escaped. This query can be injected.
    3. $_GET['id'] is PHP, therefore it cannot be part of the SQL query string unless you concatenate it:

    $query = "SELECT * FROM `table` WHERE id = " . $_GET['id'];
    {{ DiscussionBoard.errors[10524258].message }}
  • Profile picture of the author GowebMkt
    Thanks Cosmit for that detailed, yet easy to follow answer!
    {{ DiscussionBoard.errors[10524325].message }}
  • Profile picture of the author David Beroff
    Cosmit's comment about SQL injection should not be taken lightly, as you're leaving yourself wide open here. I strongly recommend that you use PDO:
    PHP: PDO - Manual

    Get to the point where you understand the humor/horror of this:
    Signature
    Put MY voice on YOUR video: AwesomeAmericanAudio.com
    {{ DiscussionBoard.errors[10529345].message }}
    • Profile picture of the author stewie-Y
      Originally Posted by David Beroff View Post

      Cosmit's comment about SQL injection should not be taken lightly, as you're leaving yourself wide open here. I strongly recommend that you use PDO:
      PHP: PDO - Manual
      I use prepared statements with MySQLi and I really like that syntax. Just curious, why do you choose PDO?
      {{ DiscussionBoard.errors[10536266].message }}
      • Profile picture of the author David Beroff
        Originally Posted by stewie-Y View Post

        I use prepared statements with MySQLi and I really like that syntax. Just curious, why do you choose PDO?
        I could probably delve into details like named parameters, but at the end of the day, my primary reason is it's an accepted standard.
        Signature
        Put MY voice on YOUR video: AwesomeAmericanAudio.com
        {{ DiscussionBoard.errors[10536288].message }}
  • Profile picture of the author stewie-Y
    Fair enough.
    {{ DiscussionBoard.errors[10536398].message }}

Trending Topics