php 如何为更新查询准备语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6514649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:36:40  来源:igfitidea点击:

How to prepare statement for update query?

phpmysqlmysqliprepared-statementbindparam

提问by Michael

I have a mysqli query with the following code:

我有一个带有以下代码的 mysqli 查询:

$db_usag->query("UPDATE Applicant SET phone_number ='$phone_number', 
street_name='$street_name', city='$city', county='$county', zip_code='$zip_code', day_date='$day_date', month_date='$month_date',
 year_date='$year_date' WHERE account_id='$account_id'");

However all the data is extracted from HTML documents so to avoid errors I would like to use a prepared statement. I found PHP documentation on bind_param()but there is no UPDATE example.

但是,所有数据都是从 HTML 文档中提取的,因此为了避免错误,我想使用准备好的语句。我找到了PHP 文档,bind_param()但没有 UPDATE 示例。

回答by Michael Berkowski

An UPDATEworks the same as an insert or select. Just replace all the variables with ?.

An 的UPDATE工作方式与插入或选择相同。只需将所有变量替换为?.

$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);

// This assumes the date and account_id parameters are integers `d` and the rest are strings `s`
// So that's 5 consecutive string params and then 4 integer params

$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();