PHP database connection encyclopedia: various database support and connection methods
Connecting to the database in PHP is an essential skill . Supports a wide range of database types, including MySQL, PostgreSQL, SQLite, etc. This article will introduce different connection methods in detail and provide practical cases.
MySQL
MySQL is one of the most popular databases. Connect to MySQL using the MySQLi extension or PDO.
MySQLi
<?php // mysqli_connect() 函数连接到 MySQL 数据库 $mysqli = mysqli_connect("localhost", "root", "password", "database_name"); // 检测连接错误 if (!$mysqli) { die("连接失败: " . mysqli_connect_error()); } ?>
PDO
<?php // PDO(PHP 数据对象)提供与所有支持的数据库连接的标准接口 try { // 创建 PDO 实例 $pdo = new PDO("mysql:host=localhost;dbname=database_name", "root", "password"); // 设置 PDO 错误模式 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die("连接失败: " . $e->getMessage()); } ?>
PostgreSQL
Use pgSQL or PDO connects to the PostgreSQL database.
pgSQL
<?php // pg_connect() 函数连接到 PostgreSQL 数据库 $pgsql = pg_connect("host=localhost port=5432 dbname=database_name user=root password=password"); // 检测连接错误 if (!$pgsql) { die("连接失败: " . pg_last_error()); } ?>
PDO
<?php try { // 创建 PDO 实例 $pdo = new PDO("pgsql:host=localhost;port=5432;dbname=database_name", "root", "password"); // 设置 PDO 错误模式 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die("连接失败: " . $e->getMessage()); } ?>
SQLite
Using SQLite3 extension Connect to SQLite database.
<?php // sqlite3_open() 函数打开 SQLite 数据库 $sqlite = new SQLite3("database.sqlite"); // 检测连接错误 if (!$sqlite) { die("连接失败: " . sqlite3_last_error()); } ?>
Practical case: Query records from MySQL database
<?php // 连接到 MySQL 数据库 $mysqli = mysqli_connect("localhost", "root", "password", "database_name"); // 执行 SQL 查询 $result = mysqli_query($mysqli, "SELECT * FROM users"); // 遍历结果集 while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"] . ",姓名: " . $row["name"] . "<br>"; } // 关闭数据库连接 mysqli_close($mysqli); ?>
The above is the detailed content of PHP database connection encyclopedia: support and connection methods for various databases. For more information, please follow other related articles on the PHP Chinese website!