将PHP PDO查询写为`dbName`.`tableName`而不是`tableName`-为什么? [英] Write PHP PDO queries as `dbName`.`tableName` as opposed to `tableName` - why?
问题描述
我正在用PHP PDO编写用户注册函数,并且发现我的查询只有在这样写的情况下才能正常运行:
I'm writing a user registration function in PHP PDO, and I have found that my query will only run fine if it is written like this:
<?php
$dbHost="localhost";
$dbName="project";
$dbUser="admin";
$dbPassword="abcd";
$dbh=new PDO("mysql:host=$dbHost;dbName=$dbName", $dbUser, $dbPassword);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query=$dbh->prepare("INSERT INTO project.users (userName, userEmail) VALUES (?,?)");
.....
另一方面,如果我这样写,它将无法运行:
On the other hand, it will not run if I write:
...
$query=$dbh->prepare("INSERT INTO users (userName, userEmail) VALUES (?,?)");
...
在这种情况下,我收到以下错误消息:
In that case, I get the following error message:
致命错误:消息为'SQLSTATE [3D000]的未捕获异常'PDOException':无效的目录名称:1046未选择数据库'在C:\ wamp \ www \ Tests \ Test03 \ Index.php:11堆栈跟踪:#0 C:\ wamp \ www \ Tests \ Test03 \ Index.php(11):PDOStatement-> execute()#1 {main}抛出于第11行的C:\ wamp \ www \ Tests \ Test03 \ Index.php >
为什么我需要精确project.users
?既然数据库名称本身已经在PDO对象中,为什么输入表名称还不够?
Why is it that I need to precise project.users
? Why isn't it enough to enter the table name, given that the db name itself is already in the PDO object?
谢谢!
JDelage
更新,请参阅下面的接受的答案.用dbname=$dbName
替换dbName=$dbName
可解决此问题.
UPDATE Please see accepted answer below. Replacing dbName=$dbName
with dbname=$dbName
solves this problem.
推荐答案
显然,PDO无法将活动数据库设置为项目",因此您需要每次都指定它.
Apparently PDO was unable to set active database to be "project" and therefore you need to specify it every time.
尝试修改您的行,使其看起来像这样:
Try to modify your line to look like this:
$dbh=new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPassword);
唯一的区别是dbname
拼写为小写而不是您的dbName
.
The only difference is that dbname
is spelled all lower-case instead of yours dbName
.
或者,在成功建立连接后执行以下SQL命令:
USE project;
,例如
Alternatively, execute this SQL command after successfully establishing a connection:
USE project;
, e.g.
$dbh->exec('USE project;');
这篇关于将PHP PDO查询写为`dbName`.`tableName`而不是`tableName`-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!