Sara Sara - 3 months ago 20
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.

<?php

$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','email@email.com')";
$query=mysqli_query($conn,$sql);
if($query)
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.

Answer

I manage to do it in following way.

Create a file name index.php with following code

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

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

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

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

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

    <input type="submit" value="Submit">
</form>
</body>
</html>

Then create another file name as insert.php

<?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
    mysqli_close($link);
?>