dongtan3395 2012-02-16 11:29
浏览 270
已采纳

如何保护ODBC查询免受SQL注入

What would be the best way to protect this query from sql injection? This example is just an example, I've read a few articles on internet but can't get my head around parametrised queries. Any links to useful articles will get a vote up but I think seeing this example would help me best.

$id = $_GET["id"];
$connection = odbc_connect("Driver={SQL Server};Server=SERVERNAME;Database=DATABASE-NAME;", "USERNAME", "PASSWORD");
$query = "SELECT id firstname secondname from user where id = $id";
$result = odbc_exec($connection, $query);
while ($data[] = odbc_fetch_array($result));
odbc_close($connection);

Thanks,

EDIT: I didn't make it obvious but I'm using SQL Server not mysql. This is just an example, it won't always be a number I'm searching on. It would be nice if the answer used parametrised queries as many people suggest this and it would be the same for all query's instead of different types of validation for different types of user input.

  • 写回答

4条回答 默认 最新

  • douren2831 2012-02-16 11:44
    关注

    Use prepared statements. First build a statement with the odbc_prepare() function, then pass the parameters to it and execute it using odbc_execute().

    This is much more secure and easier than escaping the string yourself.

    Lewis Bassett's advice about PDO is good, but it is possible to use prepared statements with ODBC without having to switch to PDO.

    Example code, untested!

    try {
      $dbh = new PDO(CONNECTION_DETAILS_GO_HERE);
      $query = 'SELECT id firstname secondname from user where id = :id';
      $stmt = $dbh->prepare($query);
      $stmt->bindParam(':id', $id, PDO::PARAM_STR);
      $result = $stmt->execute();
      $data = $stmt->fetchAll();
    } catch (PDOException $e)
      echo 'Problem: ', $e->getMessage;
    }
    

    Note: $e->getMessage(); may expose things you don't want exposed so you'll probably want to do something different on that line when your code goes live. It's useful for debugging though.

    Edit: Not sure if you wanted a PDO or ODBC example but it's basically the same for both.

    Edit: If you're downvoting me please leave a comment and tell me why.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?