The difference between execute()
and prepare()
is not that the prepare()
method has some internal flag like "secure=true;
" which will be set and magically you are save for SQL injections. In fact, you can have SQL injections with prepare()
as well when you use it wrong:
$stmt = $db->prepare('SELECT password FROM user WHERE username = "'.$username.'"');
$stmt->execute();
// ...
The point of prepared statements is that the values/arguments/variables for the SQL query are send separated from the actual SQL query to the MySQL server. This way the values/arguments/variables cannot change the SQL query you are trying to send. This prevents SQL injections where the inputs contain values like "='' OR 1 = 1 --"
.
The prepared statement is building a data structure where you set the values for the prepared statement separated via the additional API calls like bind_param()
. The SQL server will use the "prepared" statement and use the values received from bind_param()
. The query has been read, analyzed, well, it has been "prepared", and is fixed now (for the duration of this prepared statement) before even the first value with the potential dangerous data has been read. The WHERE condition cannot be altered or weakened, another SQL query cannot be appended or other rows/columns/tables can be edited.
Because of this, you cannot just redirect the execute()
call internally to prepare()
to be safe, because then you are missing the bind_param()
calls. That being said: Use execute()
when you have a fixed SQL query without any variables and/or user inputs and use prepare()
for prepared statements, where you have an SQL query which depends on variables and/or user inputs.