How to create a secure mysql prepared statement in php?

前端 未结 6 644
夕颜
夕颜 2020-11-22 03:29

I am new to using prepared statements in mysql with php. I need some help creating a prepared statement to retrieve columns.

I need to get information from different

6条回答
  •  半阙折子戏
    2020-11-22 04:04

    I agree with several other answers:

    • PHP's ext/mysql has no support for parameterized SQL statements.
    • Query parameters are considered more reliable in protecting against SQL injection issues.
    • mysql_real_escape_string() can also be effective if you use it correctly, but it's more verbose to code.
    • In some versions, international character sets have cases of characters that are not escaped properly, leaving subtle vulnerabilities. Using query parameters avoids these cases.

    You should also note that you still have to be cautious about SQL injection even if you use query parameters, because parameters only take the place of literal values in SQL queries. If you build SQL queries dynamically and use PHP variables for the table name, column name, or any other part of SQL syntax, neither query parameters nor mysql_real_escape_string() help in this case. For example:

    $query = "SELECT * FROM $the_table ORDER BY $some_column"; 
    

    Regarding performance:

    • The performance benefit comes when you execute a prepared query multiple times with different parameter values. You avoid the overhead of parsing and preparing the query. But how often do you need to execute the same SQL query many times in the same PHP request?
    • Even when you can take advantage of this performance benefit, it is usually only a slight improvement compared to many other things you could do to address performance, like using opcode caching or data caching effectively.
    • There are even some cases where a prepared query harms performance. For example in the following case, the optimizer can't assume it can use an index for the search, because it must assume the parameter value might begin with a wildcard:

      SELECT * FROM mytable WHERE textfield LIKE ?
      

提交回复
热议问题