How can I connect html form with database using Php?

Hello there,
I need some help about connecting html form with database. I have created a form for getting user info in html. Now I want to to connect it with database by using php. can anyone guide me about how can I connect it.

1 Like

Hello, William!

Assuming you have a running database on the server and a working driver for database connection (which is usually installed with your PHP anyway), you can connect to your database in the following way. Here, I’m assuming you want a bare bones scenario with no framework or ready library, like Doctrine or similar. The example below uses PDO, but you can do something similar with mysqli.

try {
    $pdo = new PDO('mysql:host=localhost;dbname=test', 'database_user',  'database_password');

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";

Now we want to try to insert our values from the form into the database:

$sql = "INSERT INTO table (column1, column2) VALUES (?,?)";
$statement = $pdo->prepare($sql);
$statement->execute([$value1, $value2]);
1 Like

Hello William, in PHP procedural method, you can do it like this below:

      $connection = mysqli_connect('localhost', 'root', ' ', 'your_database_name_here');

         if( !$connection ) {
            die("Database connecting failure". mysqli_error($connection));
          } else {
            echo "database connected successfully";

After that, you will have to write some PHP codes to collect the data using the HTML form assuming your form has the button called ‘Submit’ (but submit button input’s name property must be simple ‘submit’ which is taken by the php superglobal $_POST to understand the button behaviour like in the code below).

The related MYSQL code snippet is at the bottom of this post.


       if(isset($_POST['submit'])) {
        $your_name = $_POST['your_name'];

        $sql = "INSERT INTO your_database_table_name (your_name) VALUES 

        $result = mysqli_query($connection, $sql);

        if( $result == false ) {
         echo "Can not create data";
        else {
         echo "Data created successfully";


(Keep in mind that ‘your_database_table_name’ is a table created under the database called ‘your_database_name’ . so when you need to insert, search, update and to delete the data, you have to do them inside in the sake of the table name.)

Assuming the database created as your_database_name here is the code snippet for the your_database_table_name in MYSQL.

CREATE TABLE your_database_table_name (

    your_name VARCHAR(100) NOT NULL


Note: you have to create an ‘id’ for querying the data sequentially other than ‘your_name’ data.

Hope this will help you.