MySQL – INSERT Records with HTML Form and PHP

You can easily create an HTML form with PHP to insert records within your MySQL database.

Warning – It’s important to create a troubleshooting routine, and verify you have written your code properly.



<form action="phpForm.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
Gender: <select name="gender">
	<option value=" "> </option>
	<option value="boy">Boy</option>
	<option value="girl">Girl</option>
<input type ="submit">


phpTEST.php (Verify HTML Form and PHP are working)


$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];

echo $name."<br>".$age."<br>".$gender."<br>";



$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];

$servername = "localhost";
$username = "bob";
$password = "123456";
$db = "classDB";

$conn = new mysqli($servername, $username, $password, $db);

if ($conn->connect_error){
	die("Connection failed: ". $conn->connect_error);

$sql = "insert into students(name,age,gender) values('$name','$age','$gender')";

if ($conn->query($sql) === TRUE) {
	echo "ADDED: ".$name.", ".$age.", ".$gender;
} else {
	echo "Error: ".$sql."<br>".$conn->error;



Be the first to comment

Leave a Reply