Home > Article > Backend Development > How to solve the problem when php fails to connect to mysql
PHP can use PDO to connect to the database. The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for PHP to access databases.
<?php $dbms='mysql'; //数据库类型 $host='localhost'; //数据库主机名 $dbName='test'; //使用的数据库 $user='root'; //数据库连接用户名 $pass=''; //对应的密码 $dsn="$dbms:host=$host;dbname=$dbName"; try { $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象 echo "连接成功<br/>"; /*你还可以进行一次搜索操作 foreach ($dbh->query('SELECT * from FOO') as $row) { print_r($row); //你可以用 echo($GLOBAL); 来看到这些值 } */ $dbh = null; } catch (PDOException $e) { die ("Error!: " . $e->getMessage() . "<br/>"); } //默认这个不是长连接,如果需要数据库长连接,需要最后加一个参数:array(PDO::ATTR_PERSISTENT => true) 变成这样: $db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true)); ?>
Username and Password: Specify the username and password of the MySQL user used to connect to the MySQL database server. This account must have sufficient permissions to access the database specified above.
We will use:
Local MySQL database server, so that the DSN is localhost.
In classicmodels as a sample database.
Root account with blank password, just for demonstration.
Connecting to MySQL Steps
First, for convenience, we will create a new PHP file for database configuration, dbconfig.php. This file contains all configured parameters:
<?php $host = 'localhost'; $dbname = 'classicmodels'; $username = 'root'; $password = '';
Second, we create a new PHP file called phpmysqlconnect.php:
<?php require_once 'dbconfig.php'; try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); echo "Connected to $dbname at $host successfully."; } catch (PDOException $pe) { die("Could not connect to the database $dbname :" . $pe->getMessage()); }
How the script works
dbconfig.php uses the require_once function to include the file in the script.
In the try block, we create a new PDO object with three parameters: connection string, username and password. The connection string consists of the variables $host and $dbname in the file dbconfig.php.
If the connection to the MySQL database is successfully established, we will display a success message. If there are any errors or exceptions, PHP will issue a PDOException
containing a detailed error message. We call the object's getMesage() method PDOException to get the detailed message to be displayed.
The above is the detailed content of How to solve the problem when php fails to connect to mysql. For more information, please follow other related articles on the PHP Chinese website!