2014-06-27 14:32 阅读 22

“SELECT $ var FROM ...”中的变量,这是安全的还是对sql注入开放?

I've been learning about prepared statements and binding parameters... I had hoped to be able to do this:

SELECT ? FROM table WHERE id=?

However, I found you can't use a bound parameter to call the table or columns where searching here. And I understand the reason behind why as well now after searching here.

That leaves me with this question. Is it safe to use a variable like this:

$fields = "col1, col2, col3";  
SELECT $fields FROM table WHERE id=?

I ask, because I have a large statement, and it's nice to be able to make the statement short and use $fields which contains a very long string. I could just use select all, except that I'm then storing and then binding the results (not sure if it's necessary actually... I haven't tried to use $stmt->get_result() yet, just upgraded php to be able to use it yesterday).

I have a general idea of how SQL Injection works, and from all the reading I've been doing it seems the idea of a prepared and parametrized statement is it prevents SQL Injection by having SQL not run the whole statement, but breaks it apart to put it simply...

Yet when I put the $fields variable, is that opening it back up to SQL Injection now that I have a variable directly in the statement? $fields is hard coded, not coming from any source other than the code itself (not from user, not from database). I don't know the extent to which SQL Injections can potentially attack, which is why I'm asking here. I can deal with a long statement, but this will help me understand the proper way as well make it more secure.

Thank you.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douhui1630 douhui1630 2014-06-27 14:35

    $fields is hardcoded, not coming from any source

    This means you do not have to worry about injections at all. Even if you were using it in any other place of the statement.

    You should of course be carefull not to make it "public" later on!

    点赞 评论 复制链接分享
  • dpnzf48660 dpnzf48660 2014-06-27 14:36

    To prevent SQL injection in your query avoid to put that variable directly into the query. Instead of that you should use PDO

    See this question

    点赞 评论 复制链接分享