How to create a secure mysql prepared statement in php?

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 columns. Currently for a test file, I use the completely unsecure SQL statement:

$qry = "SELECT * FROM mytable where userid='{$_GET['userid']}' AND category='{$_GET['category']}'ORDER BY id DESC"
$result = mysql_query($qry) or die(mysql_error()); 

Can someone help me create a secure mysql statement using input from url parameters (as above) that is prepared?

BONUS: Prepared statements are suppose to increase speed as well. Will it increase overall speed if I only use a prepared statement three or four times on a page?

Here's an example using mysqli (object-syntax - fairly easy to translate to function syntax if you desire):

$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT * FROM mytable where userid=? AND category=? ORDER BY id DESC");
$stmt->bind_param('ii', intval($_GET['userid']), intval($_GET['category']));

$stmt->bind_result($column1, $column2, $column3);

    echo "col1=$column1, col2=$column2, col3=$column3 n";


Also, if you want an easy way to grab associative arrays (for use with SELECT *) instead of having to specify exactly what variables to bind to, here's a handy function:

function stmt_bind_assoc (&$stmt, &$out) {
    $data = mysqli_stmt_result_metadata($stmt);
    $fields = array();
    $out = array();

    $fields[0] = $stmt;
    $count = 1;

    while($field = mysqli_fetch_field($data)) {
        $fields[$count] = &$out[$field->name];
    call_user_func_array(mysqli_stmt_bind_result, $fields);

To use it, just invoke it instead of calling bind_result:


$resultrow = array();
stmt_bind_assoc($stmt, $resultrow);


You can write this instead:

$qry = "SELECT * FROM mytable where userid='";
$qry.= mysql_real_escape_string($_GET['userid'])."' AND category='";
$qry.= mysql_real_escape_string($_GET['category'])."' ORDER BY id DESC";

But to use prepared statements you better use a generic library, like PDO

prepare('SELECT * FROM mytable where userid=? and category=? 
                      order by id DESC');
//Consider a while and $sth->fetch() to fetch rows one by one
$allRows = $sth->fetchAll(); 

Or, using mysqli

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 ?
  • 链接地址:

    上一篇: mySQL私人/ conn问题

    下一篇: 如何在PHP中创建一个安全的MySQL准备语句?