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.html
<html>
<body>
<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>
</select><br>
<input type ="submit">
</form>
</body>
</html>
phpTEST.php (Verify HTML Form and PHP are working)
<?php
$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];
echo $name."<br>".$age."<br>".$gender."<br>";
?>
phpForm.php
<?php
$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;
}
$conn->close();
?>
Be the first to comment