How to use PHP to enter Form Data into MySQL Database

I want data entered into my html form to be stored in mysql database.

Im having trouble with the php script. Can someone offer assistance. Here in my code

Below is the Php file where the "Form action" Links to.

But when i enter information it does not store data. Any suggestion?

<?php


/*Data Base Connection 
*/
$dbServername="localhost";
$dbUsername = 'root';
$dbPassword ='';
$dbName = 'fencing';


$conn= mysqli_connect($dbServername,$dbUsername,$dbPassword,$dbName);

echo "Connection to Database Successful!!!!";

/* Insert Data in Database */

$sql= "INSERT INTO customerleadsfencing (firstname) values('$firtstname')";


if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;

} 
$conn->close();

/*Insert Form Data */

$firstname= $_POST['firstname'];
$email= $_POST['email'];
$phone= $_POST['phone'];
$address= $_POST['address'];
$city= $_POST['city'];
$state= $_POST['state'];
$zip= $_POST['zip'];


$sql= "INSERT INTO customerleadsencing (firstname,email,phone, address, city, state, zip)
   Values ('$firstname','$email','$phone','$address', '$city','$state', '$zip')";


 if(mysqli_query($conn,$sqli))

 { echo'Not Inserted';}

  Else {
  echo'Inserted'
   }



  ?>

1 answer

  • answered 2020-01-14 02:20 not_null

    Hope this helps :)

    <?php
    /*Data Base Connection*/
    $conn= mysqli_connect("localhost","root","","fencing");
    
    if(isset($_POST['submit'])){
    /*Insert Form Data */
    $firstname= $_POST['firstname'];
    $email= $_POST['email'];
    $phone= $_POST['phone'];
    $address= $_POST['address'];
    $city= $_POST['city'];
    $state= $_POST['state'];
    $zip= $_POST['zip'];
    
    if($firstname == "" || $email == "" || $phone == "" || $address == "" || $city == "" || $state == "" || $zip == ""){
    echo "All fields are required!";
    }
    else{
    $insert_query = mysqli_query($conn,"INSERT INTO customerleadsencing(firstname,email,phone,address,city,state,zip)VALUES('$firstname','$email','$phone','$address','$city','$state','$zip')")or die(mysqli_error($conn));
    }
    
    }
    ?>
    
    <!DOCTYPE html>
    <html>
    <head>
    <title>Insert Data to Database</title>
    </head>
    <body>
    
    <form method="post" action="">
    First Name:<br><input type="text" name="firstname"><br>
    Email:<br><input type="email" name="email"><br>
    Phone:<br><input type="text" name="phone"><br>
    Address:<br><input type="text" name="address"><br>
    City:<br><input type="text" name="city"><br>
    State:<br><input type="text" name="state"><br>
    Zip:<br><input type="text" name="zip"><br>
    <input type="submit" name="submit" value="Insert">
    </form>
    
    </body>
    </html>