Connecting to a Database with PHP
page 1: Introduction
page 2: Connecting to the Database
page 3: Displaying Tables
page 4: Inserting New Records
page 5: Updating Records
page 6: Deleting Records
Insert a new record
Very nice, but what if we need to add another pet into our database? Sadly, too many abandoned animals are turned into rescue centers every day, and inserting new records will be a much repeated task.
Our script starts out pretty much the same. We connect to the server, identify our connection, select our database, and submit an SQL query. This time we will use the INSERT statement, which requires that first we identify the fields, or columns, of our table, then that we list the values that will go into each of the fields.
We'll also add feedback to let the user know that the insertion was successful. Here you see a new operator, the double equal sign. If you can remember that one equal sign is an assignment operator (we are assigning a value, say, to a variable), you will understand why we need to distinguish that from a true comparison operator. Two equal signs tells us that one thing is equal to another.
After we have given our feedback, we will run the SELECT query again so that we can display our database and see that new pet for ourselves. This code will again go between the opening and closing body tags.
<?php
$connectID = mysql_connect("127.0.0.1", "root", "dancer");
mysql_select_db("animal_rescue", $connectID);
$result = mysql_query("INSERT INTO adoption_list (ID, species, breed,
name, age, personality, image)
VALUES ('', 'Cat','Himalayan', 'Sassy', 7, 'Devoted to her one person',
'sassy.jpg')", $connectID);
if ($result == TRUE)
{
print "The record was added successfully.<p>";
}
else
{
print "The record could not be added.<p>";
}
$resultID = mysql_query("SELECT species, breed, name, age, personality
FROM adoption_list", $connectID);
print "<table border=1><tr><th>Species</th><th>Breed</th><th>Name</th>
<th>Age</th><th>Personality</th></tr>";
while ($row=mysql_fetch_row($resultID))
{
print "<tr>";
foreach ($row as $field)
{
print "<td>$field</td>";
}
print "</tr>";
}
print "</table>";
mysql_close($connectID);
?>
Output to the browser, it looks like this:

What if we need to update a record to correct a mistake or change something such as an animal's name or age? Let's look at the update statement next-->>