!SQLSTATE [3D000]:无效的目录名称:1046未选择数据库

时间:2017-05-30 10:27:31

标签: php pdo

我正在处理一个pdo脚本,结果我看到"!SQLSTATE [3D000]:无效的目录名称:1046没有选择数据库"     我真的需要帮助这个cos困惑;脚本是:

 <?php

//connecting to the database
$serverhost = 'localhost';
$serverdb = 'charles';
$serveruser = 'root';
$serverpassword = '';


//using try and catch pdoexception errors

try {
    $connect = new PDO("mysql:$serverhost;serverdb=$serverdb;", $serveruser, $serverpassword);
    $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $bad = $connect->query('select * from users');
    var_dump($bad->fetchAll());
} catch (PDOException $e) {
    echo $e->getmessage();
}

if ($connect) {
    echo 'database successful!';
}
?>

4 个答案:

答案 0 :(得分:2)

PDO连接中的参数传递不正确。您需要添加host and dbname

更改

$connect= new PDO("mysql:$serverhost;serverdb=$serverdb;" , $serveruser, $serverpassword);

$connect = new PDO('mysql:host=$serverhost;dbname=$serverdb', $serveruser, $serverpassword);

阅读http://php.net/manual/en/pdo.connections.php

答案 1 :(得分:1)

您需要尝试此操作而不是$ connect line
$connect = new PDO('mysql:host=$serverhost;dbname=$serverdb', $serveruser, $serverpassword);

答案 2 :(得分:1)

您的$connect= new PDO("mysql:$serverhost;serverdb=$serverdb;" , $serveruser, $serverpassword);

语法错误

应该是 $connect = new PDO("mysql:host=yourhostname;dbname=yourdbname;" $user, $pass);

按手册说。

答案 3 :(得分:-2)

<?php

class Conexion {

    private static $conexion;

    public static function abrir_conexion(){
        if(!isset(self::$conexion)){
            try {
            include_once 'config.inc.php';

            self::$conexion = new PDO('mysql:host'.NOMBRE_SERVIDOR.':dbname=' .NOMBRE_BD, NOMBRE_USUARIO, PASSWORD);
                self::$conexion -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
            self::$conexion -> exec("SET CHARACTER SET utf8");

            } catch (PDOException $ex) {
                print "ERROR:" . $ex -> getMessage() . "<br>";
                die();
            }
        }
    }  
    public static function cerrar_conexion(){
        if(isset(self::$conexion)){
            self::$conexion = null;           
        }
    }
    public static function obtener_conexion(){
    return self::$conexion; 
    }
}