Prepared statements in MySQLi

suggest change

See Preventing SQL injection with Parameterized Queries for why prepared statements keep SQL statements separate from user data.

The $conn variable here is a MySQLi object. See MySQLi connect.

For both examples, we assume that $sql is

$sql = "SELECT column_1 
    FROM table 
    WHERE column_2 = ? 
        AND column_3 > ?";

The ? represents the values we will provide later. Do not put quotes around the placeholders. Placeholders stand for values, including values in SELECT lists, SET, VALUES, and WHERE. They cannot stand for identifiers such as column or table names, so they cannot replace the name in FROM.

Object oriented style

if ($stmt = $conn->prepare($sql)) {
  $stmt->bind_param("si", $column_2_value, $column_3_value);
  $stmt->execute();

  $stmt->bind_result($column_1);
  $stmt->fetch();
  // $column_1 now holds the first selected column of the current row. fetch() returns one row.
  $stmt->close();
}

Procedural style

if ($stmt = mysqli_prepare($conn, $sql)) {
  mysqli_stmt_bind_param($stmt, "si", $column_2_value, $column_3_value);
  mysqli_stmt_execute($stmt);
  // Fetch data here
  mysqli_stmt_close($stmt);
}

The first parameter of $stmt->bind_param or the second parameter of mysqli_stmt_bind_param is determined by the data type of the corresponding parameter in the SQL query:

Parameter Data type of the bound parameter
i integer
d double
s string
b blob

Your list of parameters needs to be in the order provided in your query. In this example si means the first parameter (column_2 = ?) is string and the second parameter (column_3 > ?) is integer.

For retrieving data, see How to get data from a prepared statement.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents