33

I have a mysqli query with the following code:

$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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Michael
  • 6,377
  • 14
  • 59
  • 91

1 Answers1

74

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

$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();
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • apart from the original question do you have any idea if the prepare statement has unicode support ? I need to store some arabic names – Michael Jun 29 '11 at 01:20
  • 3
    @ArabMichael: Make your database use UTF8 encoding, set your PHP's internal encoding to UTF8 ([iconv_set_encoding](http://php.net/manual/en/function.iconv-set-encoding.php)) and you should be fine. – Kerrek SB Jun 29 '11 at 01:34
  • 1
    Michael answers to ArabMichael :D – DJ22T May 21 '14 at 17:46
  • @DannyG Doing some archaeology? Way back then I used to go by plain Michael, and the OP as ArabMichael. – Michael Berkowski May 21 '14 at 17:53
  • Kind of that, hehe, got into this question somehow, noticed the fact and commented :) – DJ22T May 21 '14 at 20:10
  • Similar issue with a prepared update statement from a jquery get. This solved my problem – Callat Sep 04 '17 at 21:36
  • And what about scalar variable, how prepared statement is used in this way (...WHERE account_id='{$account_id}'"); – Sean Bean Oct 15 '19 at 21:54