MySQL - INSERT

A tutorial on how to use the mySQL INSERT command to insert data.

After you have a database and tables created then you can move on to inserting information into your database. There are 3 ways to get information into your database: 1. Type in records manually though phpMyAdmin 2. Entering the data through a query (this can be done by directly executing a MySQL query in phpMyAdmin or though a web form or through a form on a web page) 3. Import records from a spreadsheet. Typing records through phpMyAdmin and importing them are dealt with on the phpmyadmin tutorial page.

On this page we show you how to do it by writing a query. To do this you need to learn the MySQL INSERT command. When writing an INSERT command, string values, date values, and time values MUST be quoted and numeric values, functions, and the word "NULL" must NOT be quoted. If a column is formatted so that it cannot have a NULL value then not specifying a value will cause an error. The values inserted are separated by a single quote so if you need to insert a value that contains a single quote then it would cause a problem. To fix this you need to escape the single quote by adding a backslash. For example, to insert the last name "O'Brien" you will need to enter it as 'O\'Brien'.

The following example shows the synax for an INSERT query.

INSERT INTO tablename (column1, column 2) VALUES (value1, value2)

To insert several values at once:

INSERT INTO USERS (firstname, lastname) VALUES ('John','Smith'),('Jim','Jones'),('Martin','Gross');

On the following MySQL tutorial pages I will use a test database with the following test data. The code below can be entered through the phpMyAdmin "SQL" tab into a table called "users".

MYSQL code

$query="INSERT INTO users (firstname, lastname, age, state) VALUES
     ('John','Smith',17,'Ohio'),
     ('John','Kennedy',35,'Massachusetts),
     ('Martin','Gross',16,'Florida'),
     ('Brian','Grossman',31,'Maine'),
     ('Eric','Friedman',27,'Texas')";






 
Bookmark this page: