MySQL Insert
When data is put into a MySQL table it is referred to as
inserting data. When inserting data it is important to remember
the exact names and types of the table's columns. If you try to
place a 500 word essay into a column that only accepts integers
of size three, you will end up with a nasty error!
Inserting Data Into Your Table
Now that you have created your table, let's put some data
into that puppy! Here is the PHP/MySQL code for inserting data
into the "example" table we created in the previous lesson.
PHP & MySQL Code:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Sandy Smith', '21' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Bobby Wallace', '15' ) ")
or die(mysql_error());
echo "Data Inserted!";
?>
Display:
Data Inserted!
This code is much simpler to understand than the create table
code, as will be most of the MySQL queries you will learn in the
rest of this tutorial. Once again, we will cover the code line
by line.
'mysql_query("INSERT INTO example'
Again we are using the mysql_query function. "INSERT INTO"
means that data is going to be put into a table. The name of the
table we specified to insert data into was "example".
'(name, age) VALUES('Timmy Mellowman', '23' ) ")'
"(name, age)" are the two columns we want to add data into.
"VALUES" means that what follows is the data to be put into the
columns that we just specified. Here we enter the name Timmy
Mellowman for "name", and 23 for "age".
Be sure to note the location and number of apostrophes and
parentheses in the PHP code, as this is where a lot of beginner
PHP/MySQL programmers run into problems.
Review & Homework
If all goes as well, this .php page will add a three people
to the "example" table every time it is run. Be sure to use your
MySQL administration program provided by your web host to ensure
that the data was inserted into your table correctly.
Be careful not to run this script more than once, otherwise
you will be inserting the same people, multiple times. This is
called inserting duplicate records and is usually avoided.
|