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!
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('Putu Sanjaya', '23' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Made Sanjaya', '21' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Nyoman Sanjaya', '15' ) ")
or die(mysql_error());
echo "Data Inserted!";
?>
Display
Data Inserted!
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('Putu Sanjaya', '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 Putu Sanjaya 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.