PHP Tutorials

Insert records into a MySQL database

insert.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Insert a Quote</title>
</head>
<body>
<form method="post" action="insert.php">
first_name:<input type="text" name="first_name" id="first_name" /><br />
last_name:<input type="text" name="last_name" id="last_name" /><br />
quote:<textarea name="quote" id="quote" cols="45" rows="5"></textarea><br />
subject:<input type="text" name="subject" id="subject" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

insert.php

<?php
include("my_database_connection.php");

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$quote = $_POST['quote'];
$subject = $_POST['subject'];

$my_insert_query = "INSERT INTO my_quotes (quote_id, first_name, last_name, quote, subject)
VALUES ('', '$first_name', '$last_name', '$quote', '$subject')";

$my_insert_result = mysql_query($my_insert_query) or die ("Error message: $my_insert_query" . mysql_error());

if ($my_insert_result)
{
echo "Your quote has been inserted successfully.";
}
mysql_close();
?>

PHP Code Explanation
include("my_database_connection.php") Include (replace this line with) the contents from the external file my_database_connection.php from the same directory on the server
$author_name This new variable name $... should be used ...
$_POST['author_name']; for content posted from the text field named ...
INSERT INTO my_quotes Insert into the table name my_quotes ...
(quote_id, first_name, last_name, quote, subject) in column names (...) ...
VALUES ('', '$first_name', '$last_name', '$quote', '$subject')"; values from variables (with content of the text fields).
The first (empty) value is the record ID. A new, unique number is added by the database.
or die or exit (if there is a problem)
Error message the error message you want to display if the data cannot be inserted ...
.

plus or and, like + in JavaScript or & in ASP

mysql_error() the error message from the MySQL database on the server
my_database_connection.php
<?php
mysql_connect("your-mySQL-server.yourdomain.com","your-user-name","your-password") or die ("your error message");
mysql_select_db ("your-database-name") or die ("the database error message you want to display");
?>
PHP Tutorials
Other Tutorials