连接到数据库时PDO / PHP代码出错

时间:2017-07-06 00:41:43

标签: php mysql database pdo

我正在尝试使用PHP和PDO来创建和连接到我已经创建的MySQL数据库。一切都工作正常,除了我一直给我这个错误:

  

连接失败:PDO :: __ construct():SQLSTATE [HY000]:常规错误:错误模式无效

有人可以告诉我这个错误意味着什么。感谢。

编辑:这是草案代码。

这是connection.php

<?php
class Config
{
    public function Con()
    {
        $config = new Config();
    }
}
class Connection
{
    protected $db = null;
    public function Open()
    {
        try {
            $dsn = "mysql:dbname=cashgroup;
            host=localhost";
            $user = "root";
            $password = "newpassword";
            $options = array(PDO::ATTR_ERRMODE => 
            PDO::ATTR_DEFAULT_FETCH_MODE
            );

            $this -> db = new PDO($dsn, $user, $password,      $options);

            return $this -> db;
            } catch (PDOException $e) {
                echo 'Connection failed:' . $e ->getMessage();
            }
        }
        public function Closed()
        {
            $this -> db = null;
             return true;
        }
}
?>

这是include.php

<?php
 include 'connection.php';

try {
    $conec = new Connection();
    $con = $conec -> Open();
    if ($con) {
        echo 'connected';
        $sql = "INSERT INTO `clients`(`name`, `email`) VALUES    (`FakeName`, `fakeemail@gmail.com`)";
        $re = $con -> query($sql);
    } else {
        echo $con;
    }
 }

catch (PDOException $ex) {
    echo $ex -> getMessage();
}
?>

1 个答案:

答案 0 :(得分:0)

你搞砸了这里的属性:

$options = array(PDO::ATTR_ERRMODE => 
   PDO::ATTR_DEFAULT_FETCH_MODE
);

他们应该是这样的:

$options = array(
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);

或任何其他有效值。