Home > Database > Mysql Tutorial > body text

How to Update Data Securely in MySQL using Prepared Statements?

DDD
Release: 2024-10-31 09:10:29
Original
214 people have browsed it

How to Update Data Securely in MySQL using Prepared Statements?

Using Prepared Statements for Update Queries

When executing update queries with PHP and MySQL, it is recommended to use prepared statements to ensure data integrity and prevent SQL injection. In a recent discussion on MySQL's UPDATE statement, a user sought guidance on how to utilize prepared statements.

Solution

In MySQL, prepared statements follow a similar format to INSERT or SELECT statements. To use a prepared statement for an UPDATE query, simply replace all variable values with placeholders represented by the question mark (?):

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

Once the SQL statement is prepared, create a prepared statement object:

<code class="php">$stmt = $db_usag->prepare($sql);</code>
Copy after login

Next, bind parameters to the prepared statement. The following example assumes that the date and account_id parameters are integers (d), while the remaining parameters are strings (s):

<code class="php">$stmt->bind_param('sssssdddd', $phone_number, $street_name, $city, $county, $zip_code, $day_date, $month_date, $year_date, $account_id);</code>
Copy after login

Execute the prepared statement:

<code class="php">$stmt->execute();</code>
Copy after login

Handle any errors if they occur:

<code class="php">if ($stmt->error) {
  echo "FAILURE!!! " . $stmt->error;
}
else echo "Updated {$stmt->affected_rows} rows";</code>
Copy after login

Finally, close the prepared statement:

<code class="php">$stmt->close();</code>
Copy after login

The above is the detailed content of How to Update Data Securely in MySQL using Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!