使用PDO创建MySQL表时出错 [英] Error when creating MySQL Table with PDO

查看:87
本文介绍了使用PDO创建MySQL表时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚使用PDO创建了一个名为"test2"的MySQL数据库.现在,我正在尝试创建一个名为"Visiteurs"的表,但是看来我的代码无法正常工作.

I have just created a MySQL database named "test2" using PDO. Now I'm trying to create a table named "Visiteurs" but it seems my code do not work properly.

回显的错误是:

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

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

(我认为这是错误的),我的代码如下:

(which is wrong I think) and my code is the following:

$serveur  = "localhost";
$login = "root";
$pass = "root";

        try{
            $conn = new PDO("mysql:host = $serveur; dbname = test2", $login, $pass);

            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $codesql = "CREATE TABLE Visiteurs (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                nom VARCHAR(50) NOT NULL,
                prenom VARCHAR(50) NOT NULL,
                email VARCHAR(70)
            )";

            $conn->exec($codesql);
            echo 'Table "Visiteurs" créée !';
        }

        catch(PDOException $e) { 
            echo 'Echec : ' . $e->getMessage(); 
        }

有人可以帮助我找出错误的出处吗?

Can someone help me find where is the error?

推荐答案

除了

Althout the PDO MySQL DSN string documentation is not specific about whitespace, experience tells me that whitespace is not permitted in a DSN string. Since you have dbname = test2, the dbname is not actually being parsed and used, so PDO complains that no database was selected. Your DSN should look like the following, with no spaces between the key=value pairs:

"mysql:host=$serveur;dbname=test2"

您在注释中提到先前的连接已成功,并且您可以发出CREATE DATABASE语句.这仅是由于 default 主机为localhost且您的$serveur变量也设置为localhost的巧合. PDO可能没有解析DSN中的host=参数,而是使用localhost作为具有用户凭据的默认连接.由于CREATE DATABASE语句不需要选择数据库,因此dbname=无关紧要.

You mentioned in comments that a previous connection succeeded and you were able to issue a CREATE DATABASE statement. That was only due to the coincidence of the default host being localhost and your $serveur variable being set to localhost as well. PDO probably did not parse the host= parameter from the DSN, but instead used localhost as the default connection with your user credentials. Since a CREATE DATABASE statement does not need to have a database selected, the dbname= was irrelevant.

这篇关于使用PDO创建MySQL表时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆