怎么用php连接数据库_PHP数据库连接配置与操作方法教程

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

怎么用php连接数据库_php数据库连接配置与操作方法教程

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:
    $connection = mysqli_connect("localhost", "root", "password", "testdb");
    if (!$connection) {
        die("Connection failed: " . mysqli_connect_error());
    }
    
    登录后复制

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免费学习笔记(深入)”;

阿里云-虚拟数字人
阿里云-虚拟数字人

阿里云-虚拟数字人是什么? ...

阿里云-虚拟数字人 2
查看详情 阿里云-虚拟数字人
  • 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 = Dotenv\Dotenv::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.

以上就是怎么用php连接数据库_PHP数据库连接配置与操作方法教程的详细内容,更多请关注php中文网其它相关文章!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号