Lesson 22: 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.
If you want to see a sophisticated example of what can be made with PHP and databases, try to join our community. It's free and takes approximately one minute to sign up. You can, among other things, maintain your own profile using the form fields. Maybe you will get ideas for your own site.
This also ends the tutorial. PHP gives you many possibilities for adding interactivity to your web site. The only limit is your imagination - have fun!
|Related topics in the PHP Forum||Replies||Views|
|no database selected||1||261|
|Problem uploading data to database||4||655|
|Is database necessary?||1||591|
|File Upload Help||5||629|