Sara Sara - 2 months ago 15
MySQL Question

Get and insert Data into MySQL database using PHP with xampp on localhost

I have managed to connect to database and I manage to insert using following code.


$username = 'root';
$password = '';
$db = 'demo';

$conn = new mysqli ('localhost',$username, $password, $db) or die("unable to connect");

$sql="insert into persons (first_name,last_name,email_address) values ('sara','smith','')";
echo 'data inserted';

But the problem is that when I try to enter data using HTML form, it didn't work for me. I have tried to follow different tutorials and different answers here on stackoverflow. Can anyone please tell me the easiest way of inserting and getting data from MySQL using PHP ?

If there is any easy tutorial or blog from where i can learn and understand all this, I would love to watch or read.


I manage to do it in following way.

Create a file name index.php with following code

<!DOCTYPE html>
<html lang="en">    
<meta charset="UTF-8">    
<title>Add Record Form</title>

<form action="insert.php" method="post">

        <label for="firstName">First Name:</label>
        <input type="text" name="firstname" id="firstName">    

        <label for="lastName">Last Name:</label>
        <input type="text" name="lastname" id="lastName">    

        <label for="emailAddress">Email Address:</label>
        <input type="text" name="email" id="emailAddress">    

    <input type="submit" value="Submit">

Then create another file name as insert.php


    /* Attempt MySQL server connection. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */

    $link = mysqli_connect("localhost", "root", "", "demo");

    // Check connection

    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());

    // Escape user inputs for security
    $first_name = mysqli_real_escape_string($link, $_POST['firstname']);
    $last_name = mysqli_real_escape_string($link, $_POST['lastname']);
    $email_address = mysqli_real_escape_string($link, $_POST['email']);

    // attempt insert query execution
    $sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";

    if(mysqli_query($link, $sql)){
        echo "Records added successfully.";
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);

    // close connection