Skip to main content

Adding data to MySQL with PHP and Web Forms

By October 3, 2013September 12th, 2022No Comments

As we start to build are application we need to add users to simple demonstration database. We can add the users from an HTML form and submit the information to PHP on the Web Server.


The web page is structured as:

<title>Add User</title>
<h1>Adding MySQL User</h1>
<form action = "useradd.php" method = "post">
<label for="un">Username:</label>
<input type="text" class="input" id="un" name="username">
<label>&nbsp</label><input type="submit" value="submit" class="button">


The form submits to useradd.php using the method post. The php file needs to be in the same directory as the html page as we have not supplied a path through to the file. The PHP file it self is written like this:

 require_once 'dbconnect.php';
 echo "Connected to $host <BR>";
 $username = htmlentities($_POST['username']);
 $query = "INSERT INTO users (username) VALUES ('$username')";
 echo $query . "<BR>";
 $result = mysqli_query($dbh,$query);
 if (!$result) {
 echo "Error entering data! <BR>";
 } else {
 echo "User $username added <BR>";

The php file takes the information from fields on the form submitted to the global variable array $_POST


The dbconnect.php file contains the username and password for the database. Normally we would not want this to be in the root directory of the web server or below and I have added this to another directory. So it can be included easily add to the include_path directive in the php.ini file on the server.

The php.ini could be in /etc/ or , as in the case of SUSE, /etc/php5/apache2. I have added to the include_path the directory /etc/php5 and I have added the dbconnect.php to this directory. As well as added security in obscuring the db connection details this works in that this same information can be used for adding, removing and searching users.

 $user = 'userapp';
 $pass = '3@Gl3-3y3';
 $host = 'localhost';
 $db = 'tup';
 $dbh = mysqli_connect($host,$user,$pass,$db);
 if (!$dbh) {
 die("Error connecting!");

The video takes us through this process and is well worth a little of your time