skip to Main Content

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?

[1]
$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


  1. execute_query() is simply a shortcut that allows you to combine prepare(), bind_param(), execute(), and get_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.

    Login or Signup to reply.
  2. execute_query() is the simplest of them all. It prepares and executes the query, and returns a mysqli_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 a mysqli_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() or execute_query(), but if you want more robustness, you can bind variables by reference to the statement object using bind_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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search