使用 PHP (XAMPP) 连接到 MySQL table

Connect to MySQL table using PHP (XAMPP)

我正在尝试在 PHP 中创建一个 CRUD。 Apache 和 MySQL 仍然是 运行。

class DB
{
    static private $connection;
    const DB_TYPE = "mysql";
    const DB_HOST = "localhost";
    const DB_NAME = "crud";
    const USER_NAME = "root";
    const USER_PASSWORD = "";

    static public function getConnection()
    {
        if (static::$connection == null) {
            try {
                static::$connection =  new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
            } catch (Exception $exception) {
                throw new Exception("connection failed");
            }
        }
        return static::$connection;
    }
}

我 运行 localhost:3306

phpMyAdmin 已启动并且 运行

输出如图

输出:

我想你忘记了连接参数中的空格和符号

这是你的语法:

new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);

哪个给:

"mysqlhostlocalhostdbnamecrudroot"

这是文档中的语法:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

您的 PDO 调用看起来很奇怪。

static::$connection =  new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);

这个结构是new PDO($dsn, $user, $password);

dsn 格式如下:

mysql:dbname=testdb;host=127.0.0.1;port=3333 then , user then , password

你的dsn部分好像不对,应该是这样的:

$dsn = 'mysql:dbname='. self::DB_NAME .';host=' . self::DB_HOST ;
$user = self::USER_NAME;
$password = self::USER_PASSWORD;

$dbh = new PDO($dsn, $user, $password);