Skip to main content
PHP-MySQL

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.

HTML Form

The web page is structured as:

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

PHP

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:

<?php
 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>";
 }
 mysqli_free_result($result);
 mysqli_close($dbh);
?>

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

PHP.INI and INCLUDE_PATH

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.

<?php
 $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