Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MariaDB update query


May 16, 2021 MariaDB


Table of contents


The UPDATE command modifies an existing field by changing the value. I t uses the SET clause to specify the column to modify and to specify the new value assigned. T hese values can be expressions or default values for a field. T he DEFAULT keyword is required to set the default value. T he command can also use the WHERE clause to specify the conditions and/or ORDER BY clauses for updates in a specific order.

See the following general syntax -

UPDATE table_name SET field=new_value, field2=new_value2,...
[WHERE ...]

Execute the UPDATE command from a command prompt or using a PHP script.

Command prompt

At the command prompt, simply use the standard commandroot -

root@host# mysql -u root -p password;
Enter password:*******
mysql> use PRODUCTS;
Database changed
mysql> UPDATE products_tbl
   SET nomenclature = 'Fiber Blaster 300Z'
      WHERE ID_number = 112;
mysql> SELECT * from products_tbl WHERE ID_number='112';
+-------------+---------------------+----------------------+
| ID_number   | Nomenclature        | product_manufacturer |
+-------------+---------------------+----------------------+
| 112         | Fiber Blaster 300Z  | XYZ Corp             |
+-------------+---------------------+----------------------+      

PHP update query script

Use the mysql_query() function in UPDATE command statements -

<?php
   $dbhost = ‘localhost:3036’;
   $dbuser = ‘root’;
   $dbpass = ‘rootpassword’;
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die(‘Could not connect: ‘ . mysql_error());
   }

   $sql = ‘UPDATE products_tbl
      SET product_name = ”Fiber Blaster 300z”
      WHERE product_id = 112’;

   mysql_select_db(‘PRODUCTS’);
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die(‘Could not update data: ‘ . mysql_error());
   }

   echo “Updated data successfully
”;
   mysql_close($conn);
?>

After a successful data update, you will see the following output -

mysql> Updated data successfully