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条)

报告相同问题?

悬赏问题

  • ¥15 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao