INSERTING DATA USING A PHP SCRIPT
How To Insert Data Using a PHP Script
SQL INSERT INTO command into the PHP function mysql_query() to insert data into a MySQL table. This Code will take three parameters from the user and will insert them into the MySQL table:
Add New Record in MySQL Database
if(isset($_POST['add']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$tutorial_title = addslashes ($_POST['tutorial_title']);
$tutorial_author = addslashes ($_POST['tutorial_author']);
}
else
{
$tutorial_title = $_POST['tutorial_title'];
$tutorial_author = $_POST['tutorial_author'];
}
$submission_date = $_POST['submission_date'];
$sql = "INSERT INTO tutorials_tbl ".
"(tutorial_title,tutorial_author, submission_date) ".
"VALUES ".
"('$tutorial_title','$tutorial_author','$submission_date')";
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
<method="post" action="">
Tutorial Title |
<name="tutorial_title" type="text" id="tutorial_title"> |
Tutorial Author |
<name="tutorial_author" type="text" id="tutorial_author"> |
Submission Date [ yyyy-mm-dd ] |
<name="submission_date" type="text" id="submission_date"> |
<name="add" type="submit" id="add" value="Add Tutorial"> |
}
?>
While doing a data insert, it is best to use the function get_magic_quotes_gpc() to check if the current configuration for
magic quote is set or not. If this function returns false, then use the function addslashes() to add slashes before the
quotes. You can put many validations around to check if the entered data is correct or not and can take the appropriate action.