How to Update Data into MySQL Database
After inserting the data in the table of the database, you have to analyse the data and make some correction if needed. If you want to make some correction, you need to update data of the database. Updation is required to maintain the accuracy of the database.
To update the data in the MySQL database, you have to first create MySQL update query and execute the query using the PHP functions. There are two alternatives you can use in PHP to insert data into MySQL databases.
- mysqli_query()
- PDO::__query()
The mysqli_query() is simple function you can use in your project if you want on MySQL database in future. If you need to use another database in future, you should use PDO function as PDO supports more than twelve different types of databases.
Update Data Using MySQLi Procedural
TO update data inside the database, a query must create using the table fields and the values you want to replace for them. You can follow the examples given-below to use for your projects.
The PHP function is same, only the query is different containing the update query statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
$hostname = "localhost"; $username = "root"; $password = ""; $mydbname = "test" //make connection $dbconn = mysqli_connect($hostname,$username,$password,$mydbname); //check connection if(!$dbconn) { die("Connection Error: ".mysqli_connect_error()); } //create query //execute query and update database if(mysqli_query($dbconn, $sql)){ echo "Data Updated successfully"; }else{ echo "Could not update data " . mysqli_error($dbconn); } //close connection mysqli_close($dbconn); |
Update data using MySQLi Object-oriented
Object-oriented is the best practice to use in your project and develop a project based on PHP. You can update database by using the updation query and execute it by using PHP object-oriented programming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
$hostname = "localhost"; $username = "root"; $password = ""; $mydbname = "test" //make connection $dbconn = new mysqli($hostname,$username,$password,$mydbname); //check connection if($dbconn->connect_error) { die("Connection Error: ".$dbconn->connect_error); } //create query //execute query and update database if($dbconn->query($sql)){ echo "Table updated successfully"; }else{ echo "Table updation failed ".$dbconn->connect_error; } //close connection $dbconn->close(); |