简体   繁体   English

使用if语句使用PDO将表单数据插入数据库

[英]Inserting form data into database using PDO using if statement

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. 我想使用SQL,PHP和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? 我是否需要使用if($_SERVER["REQUEST_METHOD] == "POST")语句,以便每次有人提交表单时都可以将数据收集到数据库中?还是可以只使用$results->execute();代码块一次?为什么呢?

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 顺便说一句,请始终使用“ ===”而不是“ ==”来验证数据和类型以了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM