PHP连接数据库指南:MySQL:安装MySQLi扩展,创建连接(servername、username、password、dbname)。PostgreSQL:安装PgSQL扩展,创建连接(host、dbname、user、password)。Oracle:安装Oracle OCI8扩展,创建连接(servername、username、password)。实战案例:获取MySQL数据、PostgreSQL查询、Oracle OCI8更新记录。
PHP 与不同数据库的连接
使用 PHP 连接到不同的数据库是任何 Web 开发人员都必须掌握的技能。本文将指导您如何使用 PHP 连接到 MySQL、PostgreSQL 和 Oracle 等流行数据库。
sudo apt-get install php7.2-mysqli
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "mydb"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }
sudo apt-get install php7.2-pgsql
$servername = "localhost"; $username = "postgres"; $password = "my_password"; $dbname = "mydb"; // 创建连接 $conn = pg_connect("host=$servername dbname=$dbname user=$username password=$password"); // 检查连接 if (!$conn) { die("连接失败: " . pg_last_error($conn)); }
sudo apt-get install php7.2-oci8
$servername = "localhost/orcl"; $username = "oracle_user"; $password = "my_password"; // 创建连接 $conn = oci_connect($username, $password, $servername); // 检查连接 if (!$conn) { $e = oci_error(); die("连接失败: " . $e['message']); }
$sql = "SELECT * FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出数据 while($row = $result->fetch_assoc()) { echo "id: " . $row["id"] . " - Name: " . $row["name"] . "<br>"; } } else { echo "没有数据"; }
$sql = "SELECT * FROM users WHERE id > 10"; $result = pg_query($conn, $sql); if (pg_num_rows($result) > 0) { // 输出数据 while($row = pg_fetch_assoc($result)) { echo "id: " . $row["id"] . " - Name: " . $row["name"] . "<br>"; } } else { echo "没有数据"; }
$sql = "UPDATE users SET name = 'John Doe' WHERE id = 1"; $stmt = oci_parse($conn, $sql); if (oci_execute($stmt)) { echo "记录更新成功"; } else { echo "更新记录失败"; }
以上是PHP与不同数据库的连接:MySQL、PostgreSQL、Oracle和更多的详细内容。更多信息请关注PHP中文网其他相关文章!