Introduction
Welcome to an introduction of using HTML and PHP to build a database in MySQL, there is a few stages to this first the form page as you can see below and under would be our PHP code. I have the MySQL connection settings set for localhost which will be needed to altered as needed and a database created either by connecting to MySQL via command line or using PHPMyAdmin.
Form page
<html>
<body>
<form action="inserttest.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
city: <input type="text" name="city">
<input type="submit">
</form>
</body>
</html>
After reading this you should see how the HTML form uses the name function to hold the data and a input submit that uses 'action' or use this to POST the data into a PHP form.
MySQL
CREATE DATABASE test
CREATE TABLE people
(
firstName VARCHAR(25),
lastName VARCHAR(25),
city VARCHAR(30)
)
Here we can see the simple database we have to insert into MySQL, First we create the database and then the table and within the table we want to make 3 columns for our $_POST data using VARCHAR and (25) CHAR limit.
PHP code
<html>
<head></head>
<?php
$con = mysql_connect("localhost","root","toor");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql="INSERT INTO member (firstName, lastName, city)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[city]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
<body>
</body>
Now we look at our PHP code and we start off by making a connection to the MySQL server, there is 3 items that is needed to make the connection. First block is server location, most cases it will be "localhost". 2nd block is username and 3rd is password. The if statement gives a error function if there is a bad connection.
Selecting the database you want to connect and modify:
mysql_select_db("test", $con)
This will be your SQL command that will be used for the execution:
$SQL="INSERT INTO member (firstName, lastName, city)
Following by the Values, in the HTML form that was used the values that was assigned are POSTed to the PHP form and this is where the data is taken from the HTML form to the PHP form as variables.
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[city]')";
And finally we have the checking function to see if everything went good and echo a finishing statement.
By this Point
We should have a general understanding on how we can use HTML, PHP and MySQL together to build a database driven web site. With this in mind you should be able to rebuild into most basic forms, hope this comes in handy for someone working out how to start with SQL and PHP.
Any Questions or suggestions on how to add on to this please post up.
Hope this helps someone gain that next step.
This page was published on It was last revised on