Inserting Data
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "INSERT INTO tb_address_book (First_Name, Surname, Address) VALUES ('bill', 'gates', 'Microsoft')";
$result = mysql_query($SQL);
mysql_close($db_handle);
print "Records added to the database";
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
You met all of this code from the previous section. The only difference is the new SQL statement! What the code does is to set up some variables, open a connection to the database, and then execute the SQL query. Let's have a look at the new, and rather long, statement.
INSERT INTO … VALUES
To add records to your database, you can use the INSERT statement. There are plenty of ways to use this statement, but we'll stick with something simple: adding
new values to all of our table columns.
You start by typing the words "INSERT INTO". This can be in any case you like: upper, lower or a mix. It's easier for you to read if it's in uppercase letters.
The next thing you need is the name of a table to insert your new values into. For us, this is the table that we've called tb_address_book.
Following the name of your table, type a pair of round brackets. Inside the round brackets, you can type the names of the columns in your table:
INSERT INTO tb_address_book (First_Name, Surname, Address)
Notice how we haven't included the ID column from our table. That's because the ID column was the one we set up to be an auto-incrementing number. We don't need to worry about this column because MySQL will take care of adding 1 to this field for us.
Now that you've specified which table you want to insert values into, and specified your column names, you can add the values you want to insert.
To add values, you type the word "VALUES" after the round brackets of your column names:
INSERT INTO tb_address_book (First_Name, Surname, Address) VALUES
After the word "VALUES", you type another pair of round brackets. Inside of these brackets, you can type your values. Each value should be separated by a comma. You can use either direct text, like we've done, or variables. You can even get these values straight from your HTML form, which we'll see how to do later.
So our whole line reads:
$SQL = "INSERT INTO tb_address_book (First_Name, Surname, Address) VALUES ('bill', 'gates', 'Microsoft')";
Notice how we've surrounded all of our text with double quotes. But inside of the values round brackets, we've used single quotes.
The syntax is really this (The SQL keywords are in blue):
INSERT INTO table_name ( Columns ) VALUES ( values for columns)