Update MySQL Table data via PHP Script

We have studied how to insert data into table, how to select it and how to use WHERE clause to filter selected data. Now is the time to update a record that already exists in the table. To update existing record the UPDATE query is used Syntax of update query is as follows:

UPDATE table SET column1=new-value1, column2=new-value2

Updating MySQL table data via Object Oriented MySQLi

To update table data via MySQLi, pass the query for updating data to the query function of the mysqli object. Have a look at the following example.




Using UPDATE clause in MySQLi



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Implementing UPDATE query

$query = "UPDATE Patient ".
    "SET patient_age = 25 ".
    "WHERE patient_age < 25";
if ($connection->query($query) === TRUE) {
    echo "Record Updated successfuly.";
} else {
    echo "Unable to update record " . $connection->error;
}

$connection->close();
?>
        



Download the code

The above UPDATE query will update all the records in the Patient table where age is less than 25 by setting the age of those patient to 25. Now if you select and view the table contents, you shall see that there should be no patient with age less than 25.

Update Table data via Procedural MySQLi

Updating table data via procedural MySQLi is straight forward. Just replace mysqli object with mysqli_connect function. The following example demonstrates this concept.




Using UPDATE clause in MySQLi



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Implementing UPDATE query

$query = "UPDATE Patient ".
    "SET patient_fname = 'Elizabeth' ".
    "WHERE patient_age < 30";
if ($connection->query($query) === TRUE) {
    echo "Record Updated successfuly.";
} else {
    echo "Unable to update record " . $connection->error;
}

$connection->close();
?>
       



Download the code

The above UPDATE query will update all the records in the Patient table where age is less than 30 by setting the first name of those patient to ‘Elizabeth’. Now if you select and view the table contents, you shall see that all the patients with age less than 30 have first name ‘Elizabeth’.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .