Search code examples
phpmysqlformspdoprepared-statement

How to insert form data into PDO from HTML form?


SO I learned this from w3schools. . .however the example used data directly injected into the code. I was wondering how can I use the same code block but receive data from a form instead

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,      
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, 
email) 
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);

// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

Solution

  • I think you need learn PHP Form Handling first

    example make form.html is

    <html>
    <body>
    
    <form action="insert.php" method="post">
    Name: <input type="text" name="firstname"><br>
    Name: <input type="text" name="lastname"><br>
    E-mail: <input type="text" name="email"><br>
    <input type="submit">
    </form>
    
    </body>
    </html>
    

    then to data handling to database make insert.php

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "yaskur";
    $dbname = "test";
    
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // prepare sql and bind parameters
    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) 
                            VALUES (:firstname, :lastname, :email)");
    $stmt->execute([
        "firstname" => $_POST["firstname"],
        "lastname" => $_POST["lastname"], 
        "email" => $_POST["email"]
    ]);