Monday, April 4, 2011

In this PHP MySQL tutorial I will show you how to use basic database manipulation features in PHP.

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.tom.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);

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:
  1. $sql = "UPDATE users SET age=45 WHERE name='Tom'";
  2. $result = mysql_query($sql);
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);

0 Comments:

Post a Comment