0
try {
$results = $db->prepare("INSERT INTO Form_Data
                        (first_name, last_name, email, gender, comment)
                        VALUES
                        (?,?,?,?,?) 
                        ");
$results->bindParam(1,$fname,PDO::PARAM_STR);
$results->bindParam(2,$lname,PDO::PARAM_STR);
$results->bindParam(3,$email);
$results->bindParam(4,$gender);
$results->bindParam(5,$comment,PDO::PARAM_STR);

if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    $results->execute();
}

} catch (Exceptions $e) {
echo "Unable to insert data";
exit;
}

I want to add form data to a database using, SQL, PHP and PDO.

Do I need to use the if($_SERVER["REQUEST_METHOD] == "POST") statement so that every time someone submits the form I can collect the data into the database? Or can I just use $results->execute(); code block once ? And why?

  • You need to add more explanation regarding your problem. So, that we could come to know what is your problem, and what solution we should suggest you. –  Aug 27 '18 at 06:53
  • If you are getting your data via a form you will have to use `POST` or `GET` in order to populate your variables used in your query. – Joseph_J Aug 27 '18 at 07:08

1 Answers1

0

Why don't you test if the form is submit and only if it is you do your try/catch ?

Something like this

<?php
if (isset($_POST['submit'])) {
    try {
        $fname = $_POST['name'];
        // Your other assignments

        $results = $db->prepare("INSERT INTO Form_Data
                    (first_name, last_name, email, gender, comment)
                    VALUES
                    (?,?,?,?,?) 
                    ");
        $results->bindParam(1,$fname,PDO::PARAM_STR);
        $results->bindParam(2,$lname,PDO::PARAM_STR);
        $results->bindParam(3,$email);
        $results->bindParam(4,$gender);
        $results->bindParam(5,$comment,PDO::PARAM_STR);
        $results->execute();

    } catch (Exceptions $e) {
        echo "Unable to insert data";
        exit;
    }    
}
?>

<form method="POST">
    <label for="name">Name</label>
    <input type="text" id="name" name="name">

    // Your other input

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

</form>

By the way, always use "===" instead of "==" to verify the data AND the type learn more

Plum
  • 71
  • 1
  • 7