PHP form tutorial Phase16

Step 4 - Insert, update, delete records
________________________________________
PHP MySQL tutorial
Inserting data into the database


In this topic we will create a code to insert new records into our MySQL database. This is very similar to the select version. Also in this case we need to build up a database connection and we will use the mysql_query() function again. However in this case we will use it with an insert sql statement. Now let's try to insert a new user to our table. The sql statement is the following:

INSERT INTO users (name,city,web,age) VALUES ('Tom','Vegas','www.jjj.com',44);


Now store this SQL statements in a variable and pass this as parameter of mysql_query like this:

Code:
1. $sql = "INSERT INTO users (name,city,web,age) VALUES ('Tom','Vegas','www.tom.com',5)";
2. $result = mysql_query($sql);
3.
PHP F1

Besides this we need to check the result and inform the user if an error was occurred. A complete insert code is the following:

Updating a record

The update is almost the same as the insert. You only need to change the sql statement and use it as before:

Code:
1. $sql = "UPDATE users SET age=45 WHERE name='Tom'";
2. $result = mysql_query($sql);
3.
PHP F1


Deleting a record

As you may know it is again the same as before. Only the sql needs to be changed like this:

Code:
1. $sql = "DELETE FROM users WHERE name='Tom'";
2. $result = mysql_query($sql);
PHP F1







Explore more on PHP form creation and handling :



0 comments:

Post a Comment