我正在从MYSQL切换到PDO,在我的表单上,它不会将表单数据插入到数据库中。奇怪的是,它不会抛出任何错误,而是在不插入数据的情况下重定向到成功页面。这是我的代码:
<?php
session_start();
/*** mysql hostname ***/
$hostname = 'XXXXXXX.hostedresource.com';
/*** mysql username ***/
$username = 'XXXXXX';
/*** mysql password ***/
$password = 'XXXXXXXX';
try {
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password);
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
/*** echo a message saying we have connected ***/
//echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$loan_amount = trim($_POST['loan_amount']);
$loan_type = trim($_POST['loan_type']);
$debt_amount = trim($_POST['debt_amount']);
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$zip = trim($_POST['zip']);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
try {
$sql="INSERT INTO leads (loan_amount, loan_type, debt_amount, first_name, last_name, email, phone, zip, reg_date) VALUES (:loan_amount, :loan_type, :debt_amount, :first_name, :last_name, :email, :phone, :zip, NOW())";
$statement = $pdo->prepare($sql);
$statement->bindValue(':loan_amount', $loan_amount);
$statement->bindValue(':loan_type', $loan_type);
$statement->bindValue(':debt_amount', $debt_amount);
$statement->bindValue(':first_name', $first_name);
$statement->bindValue(':last_name', $last_name);
$statement->bindValue(':email', $email);
$statement->bindValue(':phone', $phone);
$statement->bindValue(':zip', $zip);
$statement->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
exit();
}
header('Location: /success.php');
}
?>
答案 0 :(得分:2)
问题在于语法:
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password);
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
您的构造函数末尾有一个右括号和分号,这会破坏您的代码。你需要:
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password,
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
OR
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);