配置php数据库连接需选择mysqli或pdo方法,确保扩展启用;2. mysqli支持过程和面向对象风格,通过mysqli_connect或new mysqli建立连接并检测错误;3. PDO提供跨数据库兼容性,使用DSN、用户名密码创建实例,并设置异常模式便于调试;4. 推荐用环境变量存储敏感信息,通过phpdotenv加载配置提升安全性;5. 连接后执行select 1或查询数据库名等简单语句验证连通性,并测试增删改查操作。

if you are trying to connect to a database using PHP, proper configuration and setup are essential. Here are the steps to establish a successful connection:
The operating environment of this tutorial: macBook Pro, macOS Sonoma
1. Using MySQLi (Procedural Style)
The MySQLi extension allows you to interact with MySQL databases in a procedural manner. This method is straightforward and widely supported.
- Ensure that the MySQLi extension is enabled in your php.ini file by checking for extension=mysqli.
- Use the mysqli_connect() function with parameters for server, username, password, and database name.
- Store the connection result in a variable and verify it using mysqli_connect_Error() if the connection fails.
- Example code:
2. Using MySQLi (Object-Oriented Style)
This approach uses the MySQLi class to create an instance of the connection, offering better code organization and reusability.
立即学习“PHP免费学习笔记(深入)”;
- Create a new instance of mysqli by passing host, user, pass, and database arguments.
- Check for connection errors using the connect_error Property.
- Example:
$mysqli = new mysqli("localhost", "root", "password", "testdb"); if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } - After establishing the connection, you can execute queries using methods like query() or prepare().
3. Using PDO (PHP Data Objects)
PDO provides a consistent Interface for accessing various databases, making your application more portable across different database systems.
- Ensure the PDO MySQL driver is enabled via extension=pdo_mysql in php.ini.
- Create a new PDO instance by specifying the DSN (Data Source Name), which includes the host and database name.
- Pass username and password as additional arguments.
- Set error mode to exception for easier debugging: $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);.
- Example:
try { $pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "password"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die("Connection failed: " . $e->getMessage()); }
4. Configuring Database Connection via Environment Variables
Storing credentials directly in code poses security risks. Using environment variables keeps sensitive data out of version control.
- Create a .env file in your project root and define keys like DB_HOST, DB_USER, DB_PASS, DB_NAME.
- Use a library like vlucas/phpdotenv to load these variables into $_ENV.
- access them in your connection script:
require_once 'vendor/autoload.php'; $dotenv = DotenvDotenv::createImmutable(__DIR__); $dotenv->load(); $pdo = new PDO("mysql:host=" . $_ENV['DB_HOST'] . ";dbname=" . $_ENV['DB_NAME'], $_ENV['DB_USER'], $_ENV['DB_PASS']); - This method enhances security and simplifies configuration management across environments.
5. Testing the Connection and Performing Basic Queries
After connecting, validate functionality by executing a simple query to retrieve data or check server status.
- Run a basic SELECT query such as SELECT 1 to confirm connectivity.
- For MySQLi (procedural):
$result = mysqli_query($connection, "SELECT 1"); if ($result) echo "Database reachable.";
- With PDO:
$stmt = $pdo->query("SELECT DATABASE();"); echo "Connected to: " . $stmt->fetchColumn(); - You can also test INSERT, UPDATE, or CREATE operations after confirming the link works correctly.