PHP数据对象无法连接

时间:2015-02-03 06:43:06

标签: php mysql

我是PHP初学者,尝试通过创建PDO来连接mysql数据库。 我无法从数据库中获取数据

Error : Invalid catalog name: 1046 No database selected

代码:

<?php
$config['db']=array(
                    'host'      =>'localhost',
                    'username'  =>'root',
                    'password'  => '',
                    'dbname'    =>'testing'
                    );
$db= new PDO(
                'mysql:host =   '.$config['db']['host'].';
                 dbname     =   '.$config['db']['dbname'],
                                  $config['db']['username'],
                                  $config['db']['password']
            );


$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * from Studentsdetails ";
$Data = $db->prepare($query);
try
    {
    $Data->execute();
    $Show=$Data->fetchALL(PDO::FETCH_ASSOC);
    echo '<pre>',print_r($Show),'</pre>';
    }
catch(PDOException $e)
    {
    $e->getMessage();
    //die($e->getMessage());
    echo '<pre>',print_r($e),'</pre>';
    die('Arrrgh!');
    }   
?>

2 个答案:

答案 0 :(得分:1)

用于初始化PDO对象的代码太混乱了。请尝试以下代码:

$db = new PDO('mysql:host=localhost;dbname=testing', 'root', '');

答案 1 :(得分:0)

$dsn = 'mysql:dbname='.$config['db']['dbname'].';host='.$config['db']['host'];

$dbh = new PDO($dsn, $config['db']['username'], $config['db']['password']);

试试这个你在创建$ dsn字符串

时犯了错误
<?php
$config['db']=array(
                    'host'      =>'localhost',
                    'username'  =>'root',
                    'password'  => '',
                    'dbname'    =>'testing'
                    );
$dsn = 'mysql:dbname='.$config['db']['dbname'].';host='.$config['db']['host'];
$db= new PDO($dsn, $config['db']['username'], $config['db']['password']);


$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * from Studentsdetails ";
$Data = $db->prepare($query);
try
    {
    $Data->execute();
    $Show=$Data->fetchALL(PDO::FETCH_ASSOC);
    echo '<pre>',print_r($Show),'</pre>';
    }
catch(PDOException $e)
    {
    $e->getMessage();
    //die($e->getMessage());
    echo '<pre>',print_r($e),'</pre>';
    die('Arrrgh!');
    }   
?>