PHP MySQL tutorial - Insert, update, delete records


Home - Tutorials - Databases

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

Tutorial info:


Name:PHP MySQL tutorial
Total steps:5
Category:Databases
Level:Beginner

Bookmark PHP MySQL tutorial



Bookmark and Share

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

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.  

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





Previous Step of PHP MySQL tutorialNext Step of PHP MySQL tutorial


Tags: php mysql tutorial, php mysql, php database, php, mysql, tutorial



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0125