How to connect HTML Form to MySQL Database using PHP in 4 Minutes

How to connect HTML Form to MySQL Database using PHP in 4 Minutes

Want to know, How to connect HTML Form to MySQL Database with PHP. Here I have easy and Short step to Insert Form data into a database.

Database

Now first, we need to create a database but if you don’t know how to create a database then check out How to create Database and Table in MySQL

Database Name = youtube
Table Name = account
Attribute = (id : int, username : varchar, password : varchar)

HTML Form Code

<!DOCTYPE html>
<html>
<head>
<title>Form site</title>
</head>
<body>
<form method="post" action="connect.php">
Username : <input type="text" name="username"><br><br>
Password : <input type="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

In the above HTML code, we use action="connect.php" that means we are sending data from our HTML form to connect.php.

HTML form
Your HTML form looks like this

PHP Code (connect.php)

<?php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (!empty($username)){
if (!empty($password)){
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "youtube";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);


if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_errno() .') '
. mysqli_connect_error());
}
else{
$sql = "INSERT INTO account (username, password)
values ('$username','$password')";
if ($conn->query($sql)){
echo "New record is inserted sucessfully";
}
else{
echo "Error: ". $sql ."
". $conn->error;
}
$conn->close();
}
}
else{
echo "Password should not be empty";
die();
}
}
else{
echo "Username should not be empty";
die();
}
?>

Explaining connect.php

Line 2, 3: Grab a Form data and store it in  $username and $password .

4, 5: Check, whether this username and password are empty or not. If they are not empty then we can continue a process.

6-11: Making a database connection

13-15: Check, is their error while connecting the database. If yes then show that error message and exit. Otherwise, continue a process.

18, 19: SQL query, to insert data into a database table.

20, 21: If our insert query is executed, then give a message “New record is inserted successfully”

23-25: If the query fails to execute then show an error message.

At last, we close the database connection.

And this is how we connect HTML Form to MySQL Database with PHP

And also learn, How to Display Data from MySQL Database into HTML Table using PHP

Also, watch this video.

Share this post