未定义的属性:PDO :: $ connect_error [英] Undefined property: PDO::$connect_error
问题描述
我正在尝试使用$dbc->connect_error
检查尝试连接到我的数据数据库时是否发生任何错误.我总是得到一个错误页面,上面写着:
I am trying to use $dbc->connect_error
to check if any error occurs while trying to connect to my databease. I always get an error page saying:
注意:未定义的属性:PDO :: $ connect_error 第7行的C:\ xampp \ htdocs \ add_products_processing.php
Notice: Undefined property: PDO::$connect_error in C:\xampp\htdocs\add_products_processing.php on line 7
我正在将Windows7与XAMPP v3.2.2一起使用.完整代码如下所示.我确定用户名和密码正确.有什么建议吗?
I am using Windows7 with XAMPP v3.2.2. The full code is shown below. I am sure that the username and the password are correct. Any advice?
<?php
$dsn = 'mysql:host=localhost;dbname=technoglance';
$username = 'root';
$password = 'password';
$dbc = new PDO($dsn, $username, $password);
if ($dbc->connect_error) {
die("Connection failed: " . $dbc->connect_error);
}
$main_class =filter_input(INPUT_POST, 'main_class');
$brand =filter_input(INPUT_POST, 'brand');
$model =filter_input(INPUT_POST, 'model');
$description =filter_input(INPUT_POST, 'description');
$quantity =filter_input(INPUT_POST, 'quantity');
$adding_date =filter_input(INPUT_POST, 'adding_date');
$sell_price =filter_input(INPUT_POST, 'sell_price');
$buying_price =filter_input(INPUT_POST, 'buying_price');
if(!empty($main_class)){
try{
$query = "INSERT INTO products (main_class, brand, model, description, quantity, adding_date, sell_price, buying_price ) VALUES ('$main_class', '$brand', '$model', '$description', '$quantity', now(),'$sell_price', '$buying_price' );";
// set the PDO error mode to exception
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbc->exec($query);
echo "Thank you. The record has been sent successfully.<br><br>";
}
catch(PDOException $e){
echo $query . "<br>" . $e->getMessage()."<br><br>";
}
}
else{
echo '<h1>Please use the contact form or don\'t leave an empty field!</h1>';
}
?>
推荐答案
您的代码应为
<?php
$dsn = 'mysql:host=localhost;dbname=technoglance;charset=utf8';
$username = 'root';
$password = 'password';
$dbc = new PDO($dsn, $username, $password);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// filtering omitted
if(!empty($main_class)){
$query = "INSERT INTO products (main_class, brand, model, description, quantity, adding_date, sell_price, buying_price ) VALUES (?,?,?,?,?,?,?,?);";
$data = [$main_class,$brand,$model,$description,$quantity,$adding_date,$sell_price,$buying_price];
$dbc->prepare($query)->execute($data);
echo "Thank you. The record has been sent successfully.<br><br>";}
else{
echo '<h1>Please use the contact form or don\'t leave an empty field!</h1>';
}
PDO已经报告了它的错误,不需要任何额外的代码.
并且您应该使用准备好的语句
PDO will report it's errors already, without any extra code required.
and you should be using prepared statements
这篇关于未定义的属性:PDO :: $ connect_error的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!