Blogroll

photoshop cs6 html 5 css php seo backlinks

adsense

Sunday, 9 February 2014

How to update data in a database?

In previous lessons, you have learned to insert, retrieve and delete data from a database. In this lesson, we will look at how to update a database, i.e., edit the values of existing fields in the table.

Update data with SQL

The syntax for an SQL statement that updates the fields in a table is:
 
 UPDATE TableName SET TableColumn='value' WHERE condition
 
 
It is also possible to update multiple cells at once using the same SQL statement:
 
 UPDATE TableName SET TableColumn1='value1', TableColumn2='value2' WHERE condition 

 
With the knowledge you now have from the lessons 19, 20 and 21, it should be quite easy to understand how the above syntax is used in practice. But we will of course look at an example.

Example: Update cells in the table "people"

The code below updates Donald Duck's first name to D. and changes the phone number to 44444444. The other information (last name and birthdate) are not changed. You can try to change the other people's data by writing your own SQL statements.
 <html>
 <head>
 <title>Update data in database</title>

 </head>
 <body>

 <?php
 // Connect to database server
 mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

 // Select database
 mysql_select_db("mydatabase") or die(mysql_error());
 
 // The SQL statement is built
 $strSQL = "Update people set "; 
 $strSQL = $strSQL . "FirstName= 'D.', "; 
 $strSQL = $strSQL . "Phone= '44444444' "; 

 $strSQL = $strSQL . "Where id = 22"; 

 // The SQL statement is executed 
 mysql_query($strSQL);

 // Close the database connection
 mysql_close();
 ?>

 <h1>The database is updated!</h1>
 </body>
 </html>

 
This example completes the lessons on databases. You have learned to insert, retrieve, delete and update a database with PHP. Thus, you are actually now able to make very advanced and dynamic web solutions, where the users can maintain and update a database using forms.

0 comments:

Post a Comment