3

首先,我只是将所有PHP文件都切换为使用PDO,所以很高兴。但是我不是很有经验,PHP更不用说PDO所以我遇到了问题。我在我的数据库中运行以下查询SQL,它返回正确的值。

SELECT * 
FROM table_gon_0621_516
WHERE id =  '1'

现在我PHP像这样使用它

require_once ("../Android/connect_db.php");

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$table_name = 'table_gon_0621_516';

try { 

    $names = $db->query("
        SELECT * 
        FROM `".$table_name."` 
        WHERE `id` = '1'
        ");

    $rows = $names->fetchAll(PDO::FETCH_ASSOC);
    $col_map = array_flip($rows);
    echo '<pre>', print_r($rows, true), '</pre>';
} catch (PDOException $e){
    die($e->getMessage());
}    

我在浏览器中收到此错误

SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

这是我的连接代码

<?php

$config['db'] = array (
    'host'      => 'localhost',
    'username'  => 'admin',
    'password'  => 'xxxx', //checked and correct
    'dbname'    => 'xxxx_beta' //checked and correct
);

$db = new PDO(
    'mysql:host = '.$config['db']['host'].';
    dbname = '.$config['db']['dbname'], 
    $config['db']['username'], 
    $config['db']['password']
);
?>

此页面加载正确,没有错误,我连接成功。我究竟做错了什么?

编辑

我变了

$data = $names->fetchAll(PDO::FETCH_ASSOC);

$data = $names->fetch(PDO::FETCH_ASSOC);

我仍然有同样的问题。我还更新了上面的代码以显示此更改

第二次编辑

我更改了上面的代码,现在收到一条新消息,我假设我没有连接?

4

1 回答 1

4

改变

$db = new PDO(
    'mysql:host = '.$config['db']['host'].';
    dbname = '.$config['db']['dbname'], 
    $config['db']['username'], 
    $config['db']['password']
);

$db = new PDO('mysql:host='.$config['db']['host'].';dbname='.$config['db']['dbname'], 
    $config['db']['username'], 
    $config['db']['password']
);

或者

$db = new PDO(
    "mysql:host={$config['db']['host']};dbname={$config['db']['dbname']}",
    $config['db']['username'], 
    $config['db']['password']
);

显然 MySql PDO 驱动程序不喜欢 DSN 中的空格

mysql:host='.$config['db']['host'].';dbname='.$config['db']['dbname']
          ^^                               ^^
于 2013-06-23T22:38:50.733 回答