无法使用PDO将数据插入数据库

时间:2013-10-24 18:07:51

标签: php mysql pdo params

经过消毒和验证后,工作正常。我尝试将数据插入我的数据库,但它一直在说错误:“抱歉,我们无法为您注册...正确填写表格”

$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>";
}

非常感谢任何有助于这项工作的帮助。

2 个答案:

答案 0 :(得分:0)

不确定是否是问题,但您要拨打execute()两次 无论如何,你唯一的问题是没有错误报告。启用它并仅运行每个运算符一次:

error_reporting(E_ALL);
ini_set('display_errors', 1);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$sql = "INSERT INTO users (email, firstName, surname, userName, password, userDOB) 
                   values (?, ?, ?, ?, ?, ?)";
$stm = $conn->prepare($sql));
$stm->execute([$email,$name,$surname,$username,$password,$userDOB]);
if ($stm->rowCount())
{
    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>";
}

答案 1 :(得分:0)

非常感谢你们。它有效,但这是编写此代码并避免SQL注入的最佳实践吗?

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());
    }
}