What is the difference between using execute_query()
[1] or using the prepare()
then execute()
[2] and when do we use the bind parameter and why? Like in example [2] we already gave the variables within the execute so when is the bind parameter more useful?
$stmt = $db->execute_query($Update, [$Date, $Email]);
[2]
$stmt = $db->prepare("INSERT INTO Users (Username, Email, Password, Creation_Date, VIP, Admin) VALUES (?,?,?,?,?,?)");
$stmt->execute([
$Username,
$Email,
$Password,
$Creation_date,
$VIP,
$Admin,
]);
2
Answers
execute_query()
is simply a shortcut that allows you to combineprepare()
,bind_param()
,execute()
, andget_result()
into a single call.Since you don’t have a
mysqli_stmt
object, status information about the query will be put into the$db
object. For example, instead of$stmt->affected_rows
you use$db->affected_rows
.execute_query()
is the simplest of them all. It prepares and executes the query, and returns amysqli_result
object or bool. It can be used if all you want to do is execute a simple query and get the results.prepare()
returns amysqli_stmt
object which you can execute at your own convenience. It’s more robust than the previous option. It is useful, for example, when executing the same prepared statement within a loop with different values.You can pass all params as an array to either
execute()
orexecute_query()
, but if you want more robustness, you can bind variables by reference to the statement object usingbind_param()
. There are not many uses for it, but it’s there if you need it. It was also the only option available until PHP 8.1.