Home >Database >Mysql Tutorial >How to Create a Prepared Statement for an Update Query in PHP with mysqli?

How to Create a Prepared Statement for an Update Query in PHP with mysqli?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 17:29:02870browse

How to Create a Prepared Statement for an Update Query in PHP with mysqli?

How to Prepare a Statement for an Update Query

Problem:

To prevent errors while updating data, you want to use a prepared statement with mysqli but are unsure how to do so in the context of an update query.

Solution:

An update prepared statement in PHP follows the same pattern as an insert or select statement. Replace all variables in the query with question marks (?) and use bind_param() to assign values to the placeholders:

<code class="php">$sql = "UPDATE Applicant SET phone_number=?, street_name=?, city=?, county=?, zip_code=?, day_date=?, month_date=?, year_date=? WHERE account_id=?";

$stmt = $db_usag->prepare($sql);

// Assign values to placeholders with bind_param()
$stmt->bind_param('sssssdddd', $phone_number, $street_name, $city, $county, $zip_code, $day_date, $month_date, $year_date, $account_id);
$stmt->execute();

if ($stmt->error) {
  echo "FAILURE!!! " . $stmt->error;
}
else {
  echo "Updated {$stmt->affected_rows} rows";
}

$stmt->close();</code>

Note: In the above example, we assume that the date and account_id parameters are integers (d) while the rest are strings (s). You can adjust the parameter types accordingly.

The above is the detailed content of How to Create a Prepared Statement for an Update Query in PHP with mysqli?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn