Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepare statement for update query? [duplicate]

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.

like image 623
Michael Avatar asked Jun 29 '11 00:06

Michael


People also ask

Can we use prepared statement for update query?

The Statement. executeUpdate method works if you update data server tables with constant values. However, updates often need to involve passing values in variables to the tables. To do that, you use the PreparedStatement.

How does on duplicate key update work?

ON DUPLICATE KEY UPDATE is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE. The row/s affected value is reported as 1 if a row is inserted, and 2 if a row is updated, unless the API's CLIENT_FOUND_ROWS flag is set.

How do I use insert on duplicate key update?

The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.


1 Answers

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(); 
like image 65
Michael Berkowski Avatar answered Sep 21 '22 23:09

Michael Berkowski