MySQLi UPDATE

The MySQL UPDATE statement is used to change or modify the existing records in a database table. This statement is ordinarily utilized in conjugation with the WHERE clause to apply the changes to just those records that matches specific criteria.

Syntax

UPDATE Tablename SET column1 = value1, column2 = value2 [WHERE Clause];

These are the following ways to update data in 'employee' table -


Object Oriented PHP MySQLi Update Data

The following code updates the 'employee' data using PHP MySQLi object-oriented way. In the given example, the PHP code updates the 'emp_name' of a person in the employee table whose 'emp_id' is equal to 2.

<?php
$conn = new mysqli('hostname', 'username', 'password', 'databasename');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
$update = "UPDATE employee SET emp_name = 'Smith' WHERE emp_id = '2' ";
if($conn->query($update)){
 echo 'Data updated successfully';
}
?>




Procedural PHP MySQLi Update Data

The following code updates the 'employee' data using PHP MySQLi procedural way. The given PHP code updates the 'emp_name' of a person in the employee table whose 'emp_id' is equal to 2.

<?php
$conn = mysqli_connect('hostname', 'username', 'password', 'databasename');
//Check for connection error
if(mysqli_connect_error()){
  die("Error in DB connection: ".mysqli_connect_errno()." - ".mysqli_connect_error());
}
$update = "UPDATE employee SET emp_name = 'Smith' WHERE emp_id = '2' ";
if(mysqli_query($conn, $update)){
  echo 'Data updated successfully';
}
?>
    

Prepared PHP MySQLi Update Statement

The following code updates the 'employee' data using PHP MySQLi prepared statement.

<?php
$conn = new mysqli('hostname', 'username', 'password', 'databasename');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
$empid = '2';
$query = "UPDATE employee SET emp_name = 'Smith' WHERE emp_id = ? ";
$update = $conn->prepare($query);
$update->bind_param('i', $empid);
$result = $update->execute();
if($result){
 echo 'Data updated successfully';
}
?>    
    






Read more articles


General Knowledge



Learn Popular Language