无法使用PDO将数据插入数据库 [英] Can't Insert Data into Database using PDO

查看:128
本文介绍了无法使用PDO将数据插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过消毒和验证后,效果很好.我尝试将数据插入数据库中,但始终显示错误:抱歉,我们无法为您注册...正确填写表格"

After sanitizing and validation, which works fine. I tried inserting data into my database but it keeps saying error: "Sorry, we were not able to sign you up... Refill the form properly"

$qry = "INSERT INTO users (email, firstName, surname, userName, password, userDOB) values (?, ?, ?, ?, ?, ?)";

$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));

$q->bindParam(1, $email);
$q->bindParam(2, $name);
$q->bindParam(3, $surname);
$q->bindParam(4, $username);
$q->bindParam(5, $password);
$q->bindParam(6, $userDOB);

$q->execute();
if(!$q->execute()) {
echo "<h1> Sorry, we were not able to sign you up... Refill the form properly </h1>";
}
else {
echo "<h1> Congratulations, $name ! You have been successfully signed up! </h1>";
}

任何帮助完成这项工作的帮助将不胜感激.

Any help that will make this work would be greatly appreciated.

推荐答案

非常感谢.它行得通,但这是编写此代码并避免SQL注入的最佳实践吗?

Thank you guys a whole lot. It works, but is this best practice to write this code and to also avoid SQL Injection?

try {
        $conn = new PDO('mysql:host=localhost; dbname=userdetails', 'root', ''); 
        $conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo 'Connected!';
    }
catch(PDOException $pe) {
        echo('Connection error, because: ' .$pe->getMessage());
    }

//Insert data to Database if values are not empty and sanitized
if (!empty($_POST["firstName"]) && !empty($_POST["surname"]) && !empty($_POST["email"]) 
&& !empty($_POST["userName"]) && !empty($_POST["password"]) && $dob_day > 0 && $dob_month > 0 && $dob_year > 0)
{
    $qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values (?, ?, ?, ?, ?, ?)";

    $q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));

    $q->bindParam(1, $email);
    $q->bindParam(2, $name);
    $q->bindParam(3, $surname);
    $q->bindParam(4, $username);
    $q->bindParam(5, $password);
    $q->bindParam(6, $userDOB);

    try {
    $q->execute();
                echo "<h1> Congratulations, $name ! You have been successfully signed up! </h1>";
    }
    catch(PDOException $pe) {
        echo('Connection error, because: ' .$pe->getMessage());
    }
}

这篇关于无法使用PDO将数据插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆