Home > Tutorials > php > Inserting Data Into A Database
A tutorial on inserting data into your database.
This tutorial assumes you have basic knowledge of PHP and you have access to a MySQL database that has already got tables, Also you can connect to your database.
For this tutorial we going to create a form to insert news items into our table you will need to change the variables to match your own.
First connect to your database:
<?php
// include connect to database details
require ('config/globel.php');
?>
Now we will check if the form has been submitted if it has then the content is added to the database if the form has not been submitted then you receive an error message asking you to fill in the fields.
<?php
if (isset($_POST['submit'])) {
?>
The form has been submitted if isset which will be true when submit is clicked. So start the validation process:
<?php
//start validation input
// check fields are not empty
$newsContent = trim($_POST['newsContent']);
if (empty($newsContent)) {
$error['newsContent'] = 'Please enter your content.';
}
if (empty($newsTitle)) {
$error['newsTitle'] = 'enter a title.';
}
?>
We first trim any whitespace from the field using the trim function which removes any whitespace before or after the text.
To get the data from the form you need to post the data and add it to a variable if the form was sent using get then you would use $_GET. If the form was sent via post then use $_POST.
In this case I used post to send the form so to get the date and add it to a variable use
<?php
$newsContent = trim($_POST['newsContent']);
?>
you could equally have used
<?php
$newsContent = $_POST['newsContent'];
?>
that would have posted the data but not removed any whitespace.
Now check so see if the entry newsContent is empty using an if statement
If the data is empty then add en error message to the error array
<?php
$error['newsContent'] = 'Please enter your content.';
?>
This error will be printed above the form if there is an error. Repeat this process for all fields you want to validate.
After all validation we check to see if there has been an error:
<?php
// if validation is okay then carry on
if (!$error) {
$newsID = $_POST['newsID'];
$newsTitle = $_POST['newsTitle'];
$newsContent = $_POST['newsContent'];
?>
If there was no error then carry on and post all the form data again adding the form data to a variable. But if there was an error stop the script and show the errors.
Now we check to see if magic quotes are active on the server by using the not ! operator and if they are not active then use the function addslashes to combat problematic characters.
<?php
if(!get_magic_quotes_gpc())
{
$newsTitle = addslashes($newsTitle);
$newsContent = addslashes($newsContent);
}
?>
Now we add the data into the database using a MySQL query
First create a variable with a name to perform the query usually '$query' then using the command INSERT INTO which will insert the information then select a table to use in this case 'table-name
Tell MySQL which fields to insert data into
<?php
'(newsTitle, newsContent)'
?>
then the value of these feilds
<?php
VALUES ('$newsTitle', '$newsContent')
?>
Then use the command mysql_query the variable that ran the query in this case ($query) or die which means if the query failed then ask MySQL to tell you why it failed.
If the data was added then show a success message
<?php
// update the article in the database
$query = "INSERT INTO table-name (newsTitle, newsContent) VALUES ('$newsTitle', '$newsContent')";
mysql_query($query) or die('Error : ' . mysql_error());
echo "<p>$newsTitle Added ";
?>
Now close the brackets for errors and form submit to end the php section and then show any errors if they are set.
<?php
} //end validation
} // end form submitted
// input validation checks input not empty
if (isset($error['newsTitle'])) {
echo "<p><span class="warning">".$error['newsTitle']."</span></p> ";
}
if (isset($error['newsContent'])) {
echo "<p><span class="warning">".$error['newsContent']."</span></p> ";
}
?>
Using an if statement check to see if an error has been set and if it has show the error. I have used css to style the error but its not needed for it to work.
Now show the form. This is a simple form asking for a title and content for the news item
<?php
<form method="post" action="<?php $_SERVER['PHP_SELF'];?>">
<p><legend>Add News</legend></p>
<p>Title<input name="newsTitle" type="text" size="40" maxlength="255" ></p>
<p>Short Description<br><textarea name="newsContent" cols="60" rows="15"></textarea></p>
<p><input type="submit" name="submit" value="Add News">
</p>
</form>
?>
The form will be sent to the same page using
<?php $_SERVER['PHP_SELF'];?>
for the form action.
Here's the full code
<?php
// include connect to database details
require ('config/globel.php');
if (isset($_POST['submit']))
{
//start validation input
// check fields are not empty
$newsContent = trim($_POST['newsContent']);
if (empty($newsContent)) {
$error['newsContent'] = 'Please enter your content.';
}
if (empty($newsTitle)) {
$error['newsTitle'] = 'enter a title.';
}
// if validation is okay then carry on
if (!$error) {
$newsID = $_POST['newsID'];
$newsTitle = $_POST['newsTitle'];
$newsContent = $_POST['newsContent'];
if(!get_magic_quotes_gpc())
{
$newsTitle = addslashes($newsTitle);
$newsContent = addslashes($newsContent);
}
$newsTitle = htmlspecialchars($newsTitle);
$newsContent = htmlspecialchars($newsContent);
// update the article in the database
$query = "INSERT INTO table-name (newsTitle, newsContent) VALUES ('$newsTitle', '$newsContent')";
mysql_query($query) or die('Error : ' . mysql_error());
echo "<p>$newsTitle Added ";
} //end validation
} // end form submitted
// input validation checks input not empty
if (isset($error['newsTitle'])) {
echo "<p><span class="warning">".$error['newsTitle']."</span></p> ";
}
if (isset($error['newsContent'])) {
echo "<p><span class="warning">".$error['newsContent']."</span></p> ";
}
?>
<form method="post" action="<?php $_SERVER['PHP_SELF'];?>">
<p><legend>Add News</legend></p>
<p>Title<input name="newsTitle" type="text" size="40" maxlength="255" ></p>
<p>Short Description<br><textarea name="newsContent" cols="60" rows="15"></textarea></p>
<p><input type="submit" name="submit" value="Add News">
</p>
</form>
?>
Posted on Saturday, February 23rd, 2008 viewed 161 times, 4 Comments
Dan wrote:
Dave, any chance on you doing a tutorial on the SQL command UPDATE pls? watched the one on Lynda.com and that don't even make sense :P
Posted on Friday, March 14th, 2008
Nutty Coder wrote:
Sure thing i'll do it shortly.....
Posted on Friday, March 14th, 2008
Dan wrote:
Nuttycoder to the rescue :P
Posted on Saturday, March 15th, 2008
Nutty Coder wrote:
haha yeah as always :p I've written the tutorial
Posted on Saturday, March 15th, 2008