首先,我只是将所有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);
我仍然遇到同样的问题。我还更新了上面的代码以显示此更改
第二次编辑
我更改了上面的代码,现在收到一条新消息,我假设我没有连接?
答案 0 :(得分: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']
^^ ^^