Home >Database >Mysql Tutorial >How to implement update query in MySQL?
MySQL UPDATE query is used to update existing records in the table in the MySQL database. It can be used to update one or more fields simultaneously. And can be used to specify any condition using WHERE clause. (Related recommendation: "MySQL Tutorial")
The basic syntax of UPDATE update query is
Where Update
Implementation of Query:
Let us consider the following table "Data", which contains four columns "ID", "FirstName", "LastName" and "Age".
To update the "Age" of the person whose "ID" is 201 in the "Data" table, we can use the following code:
Use Procedure method update query:
<?php $link = mysqli_connect("localhost", "root", "", "Mydb"); if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } $sql = "UPDATE data SET Age='28' WHERE id=201"; if(mysqli_query($link, $sql)){ echo "Record was updated successfully."; } else { echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } mysqli_close($link); ?>
Output: Updated table
Output on web browser:
Update the query using the object-oriented method:
<?php $mysqli = new mysqli("localhost", "root", "", "Mydb"); if($mysqli === false){ die("ERROR: Could not connect. " . $mysqli->connect_error); } $sql = "UPDATE data SET Age='28' WHERE id=201"; if($mysqli->query($sql) === true){ echo "Records was updated successfully."; } else{ echo "ERROR: Could not able to execute $sql. " . $mysqli->error; } $mysqli->close(); ?>
Update the query using the PDO method:
<?php try{ $pdo = new PDO("mysql:host=localhost; dbname=Mydb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ die("ERROR: Could not connect. " . $e->getMessage()); } try{ $sql = "UPDATE data SET Age='28' WHERE id=201"; $pdo->exec($sql); echo "Records was updated successfully."; } catch(PDOException $e){ die("ERROR: Could not able to execute $sql. " . $e->getMessage()); } unset($pdo); ?>
This article This article is an introduction to MySQL update query. I hope it will be helpful to friends in need!
The above is the detailed content of How to implement update query in MySQL?. For more information, please follow other related articles on the PHP Chinese website!