Home > Articles > Programming > PHP

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Inserting Data

Once the table is created, we can start to populate it with event information. Eventually, we'll create a form that takes event information, but for now, we just want to add information to the table so we can discuss getting it back out again. Create a couple of static SQL statements, as shown in Listing 3.

Listing 3—Adding Records to the Events Table (saveevent.php)

<?php
// Connect to database.
$connection = mysql_connect ( "localhost", "myusername", "mypassword" ) ||
   die ( "Error connecting to database!" );

$insert_statement =
   "insert into events ".
   "(eventMonth, eventDay, eventYear, eventTitle, eventDesc)".
   " values ".
   "(12, 14, 2002, 'Christmas Tree Sale begins',".
   " 'The Illustrious Order of the Imperial Feather begins selling".
   " Christmas trees and hot chocolate in the parking lot behind".
   " their headquarters. All proceeds will go to the Homeless".
   " Goldfish Society. Sale ends December 24.')";

if (mysql_db_query ( "mysql", $insert_statement)) {
  echo("<p>Event added.</p>");
} else {
  die ("Cannot add event.");
}

$insert_statement =
   "insert into events ".
   "(eventMonth, eventDay, eventYear, eventTitle, eventDesc)".
   " values ".
   "(12, 14, 2002, 'Indoor Bathtub Regatta',".
   " 'The Sail Boating Club will be holding the 37th Annual Indoor".
   " Bathtub Regatta at 3pm. The theme this year is ''Tulips and".
   " Tugboats.''')";

if (mysql_db_query ( "mysql", $insert_statement)) {
  echo("<p>Event added.</p>");
} else {
  die ("Cannot add event.");
}
?>

Like the table-creation statement, an insert statement doesn't necessarily have to return a value, so we can simply execute it using the mysql_db_query() function, just as we did before. Notice also that we haven't specified an eventid value, because we created eventid as an AUTOINCREMENT column. If your database structure doesn't allow for the automatic creation of an identifier, of course, you would need to include logic to supply one.

Later, we'll add a form to this page, so for now save it as saveevent.php and open it in the browser. Figure 3 shows the results.

Figure 3Figure 3 Creating the two events should show two "success" messages.

  • + Share This
  • 🔖 Save To Your Account