Inserting data into a database

David Carr

Tutorials PHP & MySQL

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. Also you can connect to your database.

Here is the table structure I will be using for this tutorial.

<?php

$sql = mysql_query("CREATE TABLE news (
newsID INT NOT NULL AUTO_INCREMENT,
newsTitle VARCHAR(255) NOT NULL,
newsCont TEXT NOT NULL,
PRIMARY KEY (newsID)
) ENGINE = MYISAM")or die(mysql_error());

?>

For this tutorial I'm going to create a form to insert news items into the news 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
if (empty($newsTitle)) {
$error['newsTitle'] = 'enter a title.';
}

$newsContent = trim($_POST['newsContent']);
if (empty($newsContent)) {
$error['newsContent'] = 'Please enter your content.';
}
?>

We first trim any white space from the field using the trim function which removes any white space 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

<pre lang="php">
<?php
$newsContent = $_POST['newsContent'];
?>

 that would have posted the data but not removed any white space.
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) {
$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. Notice I haven't includes the newID as this is set to auto increment in the table and will be inserted automatically.

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 

'(newsTitle, newsContent)'

then the value of these fields

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

// 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 "<h1>$newsTitle Added</h1> ";

Now close the brackets for errors and form submit to end the PHP section and then show any errors if they are set.

} //end validation
} // end form submitted

// input validation checks input not empty
if (isset($error['newsTitle'])) {
echo "<p><span class="warning">".$error['newsTitle']."</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

<form method="post" action="<?php $_SERVER['PHP_SELF'];?>">
<h2>Add News</h2>
<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
if (empty($newsTitle)) {
$error['newsTitle'] = 'enter a title.';}
$newsContent = trim($_POST['newsContent']);

if (empty($newsContent)) {
$error['newsContent'] = 'Please enter your content.';
}

// if validation is okay then carry on
if (!$error) {

$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'];?>">
<h2>Add News</h2>
<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>

?>

if (isset($error['newsContent'])) {
echo "<p><span class="warning">".$error['newsContent']."</span></p> ";
}
?>

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.