ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

SQL UPDATE Statement

sqltuts

A user  can do so by using SQL UPDATE Statement. This will help in modifying  any field value of any MySQL table in a given database. There might be a situation when an  existing data in a MySQL table needs to be modified.

 

Basic syntax which is used to update the given table

  1. UPDATE table_name SET field1=modified-value1, field2=modified-value2
  2. [WHERE Clause]

 

The WHERE clause is used  when  a user wants to update selected rows in the desired table.

Updating Data from Command Prompt:

This will use SQL UPDATE Statement with WHERE clause to update selected data into MySQL table tutorials_table.

 

Example:

This will update tutorial_name field for a record having tutorial_id as 15.

  1. root@host# mysql -u root -p password;
  2. Enter password:*******
  3. mysql> use Database TUTORIALS;
  4. Database changed
  5. mysql> UPDATE Dtabase tutorials_table
  6.     -> SET Database tutorial_title='PHP'
  7.     -> WHERE tutorial_id=15;
  8. Query OK, 1 row affected (0.04 sec)
  9. Rows matched: 1  Changed: 1  Warnings: 0
  10.  
  11. mysql>

 

Updating Data Using PHP Script:

SQL UPDATE command can be used with or without WHERE CLAUSE into PHP function mysql_query().

 

This function will itself execute SQL command in the same way as it is executed at mysql> prompt.

Example:

  1. <?php
  2. $dbhost = 'localhost';
  3. $dbusername = 'root';
  4. $dbpassword = 'rootpassword';
  5. $conn = mysql_connect($dbhost, $dbusername, $dbpassword);
  6. if(! $con )
  7. {
  8.   die('Could not connect: ' . mysql_error());
  9. }
  10. $sql = 'UPDATE tutorials_table
  11.        SET tutorial_title="PHP"
  12.        WHERE tutorial_id=15';
  13.  
  14. mysql_select_db(' Database TUTORIALS');
  15. $retval = mysql_query( $sql, $con );
  16. if(! $result )
  17. {
  18.   die('Could not update data: ' . mysql_error());
  19. }
  20. echo "Updated data successfully\n";
  21. ?>
Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!