Writing Form Data to a MySQL Database using PHP

Alert!: Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

In this tutorial, we will make a form and then submit what is entered to a MySQL database, and learn how to carry values between pages.

Let’s make a skeleton:


<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>

</body>
</html>

Now, we need to make our form!
We will leave the action blank because it is the same as the page itself. The method is post.


<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
</body>
</html>

Ok, so we now have our form set up. Now we have to learn conditionals in PHP. This is where the real power of PHP comes into play. The basic conditional follows this format:


if ($variable == “string”) {
echo “foo”;
} else {
echo “bar”;
}

The above code tells PHP to find the value of $variable, and compare it to “string”. If the value of $variable is indeed “string”, then the script will do whatever is between the following brackets. In this case, it will print “foo”. Otherwise, it will print “bar”.

You can also stick something between the if and the else. This is an “elseif”.


if ($variable == “string”) {
echo “Foo”;
} elseif ($variable == “secondstring”) {
echo “foobar”;
} else {
echo “bar”;
}

The elseif works like a second resort. If $variable does not equal “string”, then it will see if the value of $variable is instead equal to “secondstring”. If it does, then it executes the code between the brackets. If it doesn’t, then it goes to the else. You can have an unlimited number of elseifs in a conditional.

Here are some basic things that you can use as tests in your conditionals (the code between the parentheses in the if() part):

FYI $var == “string” – This tests if the variable matches the string exactly
$var == 1 – This tests if the variable matches the number exactly
$var != “string” – This tests of the variable does NOT match the string
$var != 1 – This tests of the variable does NOT match the number
isset($var) – this tests if the variable exists and contains a value.
!isset($var) – This tests if the variable does NOT exist
$var – This tests if the variable is set to a “true” value (1 or true)
!$var – This tests if the variable is NOT set to a “true” value (1 or true)

In conditionals, you can end and recommence the PHP code between the brackets as you like. Example:


<?php
$foo = “potato”;

if (isset($foo)) {
?>
This variable exists.
<?php
} else {
?>
This variable does <i>not</i> exist.
<?php
}
?>

This would print “This variable exists.” because of the fact that $foo is set to “potato”. If we hadn’t set it at the beginning, then the script would print “This variable does not exist.”

Now, we will move on to $_POST global variables.
When a PHP script is the action of a form with a “post” method, the inputted data is set as $_POST variables.
For example, if this was our form:


<form action=”send.php” method=”post”>
<input type=”text” name=”cheese”><br>
<input type=”submit” name=”submit” value=”Submit”>
</form>

then send.php would automatically have TWO variables set.

These are:
$_POST[‘cheese’] and $_POST[‘submit’].

The $_POST global variable follows this format:
$_POST[‘inputname’]

When a submit button is clicked, its $_POST variable is automatically set. Remember how we test that with a conditional?
Let’s assume I entered “swiss” in the field named “cheese” and I clicked submit. We will make the action, send.php, test to see whether or not the form was submitted. Then, we will print what I entered in the cheese field.


<?php
if (isset($_POST[‘submit’])) {
echo $_POST[‘cheese’];
}
?>

Ok, so now we will put this to use in our main page.
We will use a !isset conditional to display the form only if it has not been submitted already.


<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
}
?>
</body>
</html>

So now the form is only displayed if it has not been submitted already.

We will now begin to learn the act of submitting our form data to our MySQL database.

Let’s start by setting our database host, username, password, and name as variables at the top.
I will be using the following as my database information:
Host: localhost
Username: lefteh
Password: 1234
Name: MyDB

We’ll set the variables before anything else, just for clarity’s sake.


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
}
?>
</body>
</html>

Now, how to connect to a MySQL database:


mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);

This code connects to your database using the first three variables, and then it selects the database that is the name of your fourth variable.

Let’s add that to our page.


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
}
?>
</body>
</html>

Now we have a page that is connected to our database and displays a form if the same has not yet been submitted.
But what if it has been submitted?

Here, we will add an “else” clause.


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
} else {

}
?>
</body>
</html>

So now, we need to do two things:
1. Write the inputted data into the database
2. Display a success message

Writing data to a MySQL database in PHP is actually quite easy:


mysql_query(“INSERT INTO `tablename` (fieldOne, fieldTwo) VALUES (‘$varone’, ‘$vartwo’)”);

That’s all! Let’s implement it in our code. We will assume that our database table name is “colors” and the fields are named “name” and “favoriteColor”. Remember our $_POST variables? We’ll set those to basic variables for simplicity’s sake and use them as the input variables. Some versions of browsers, servers, and PHP automatically do this. Just to be on the safe side, we will manually do it.


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
} else {
$name = $_POST[‘name’];
$color = $_POST[‘color’];
mysql_query(“INSERT INTO `colors` (name, favoriteColor) VALUES (‘$name’, ‘$color’)”);
}
?>
</body>
</html>

Good!

Now all we need to do is add a little success message:


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
} else {
$name = $_POST[‘name’];
$color = $_POST[‘color’];
mysql_query(“INSERT INTO `colors` (name, favoriteColor) VALUES (‘$name’, ‘$color’)”);
echo “Success! Your favourite colour has been added!”;
}
?>
</body>
</html>

And that’s all there is to it!

Leave a Reply

Your email address will not be published. Required fields are marked *