Apr 20, 2008

PHP SQL Insert Query

PHP SQL Insert Query

The insert query is used to add entries to the database. Any field value not specified here will be set to the default value for the field. The below example shows how this is done.

In my example, I am creating a web site that is a directory of web links. The database to support this effort includes the following fields:

  • url - The internet address of the web page referenced.
  • sitetitle - The title of the web page referneced.
  • description - The description of the web page referenced.
  • gifurl - The optional internet address of a graphic url to be displayed with the link.
  • cat1 - The category the link belongs in
  • email - The email of the link creator.
  • creator - The alias of the link creator.
  • id - The unique id value of the link.
  • entdate - The date the link was created.
  • sitetype - The type of site this is such as commercial, educational, or government.

The code below creates a new entry into my database setting values as shown. The values of $ure, $title, $description, $gifurl, $category, $email. $uname, and $stype were created earlier from a form submission. These values are automatically available to the PHP page processing the form input. The CURDATE() function generates a date string with a value of the current date.

$dbuser="username";
$dbpass="password";
$dbname="mydata"; //the name of the database
$chandle = mysql_connect("localhost", $dbuser, $dbpass)
or die("Connection Failure to Database");
mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found. " . $dbuser);
$mainsection="links"; //The name of the table where web links are stored
$query1="insert into " . $mainsection . " (url, sitetitle, description, gifurl, cat1, email, creator, id, entdate, sitetype) values (\"" . $url . "\",\"" . $title . "\",\"" . $description . "\",\"" . $gifurl . "\",\"" . $category . "\",\"" . $email . "\",\"" . $uname . "\"," . $i2 . ", CURDATE()," . $stype . ")";
mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1);

No comments:

Post a Comment

Popular Posts