php如何調(diào)用數(shù)據(jù)庫(kù)

PHP
小億
81
2024-09-03 19:22:44

在PHP中,可以使用PHP Data Objects (PDO) 或 MySQLi擴(kuò)展來(lái)連接和操作數(shù)據(jù)庫(kù)。這里是一個(gè)簡(jiǎn)單的示例,展示了如何使用PDO連接到MySQL數(shù)據(jù)庫(kù)并執(zhí)行查詢(xún)。

  1. 首先,確保已經(jīng)安裝了PDO和MySQL擴(kuò)展。在php.ini文件中取消以下行的注釋?zhuān)?/li>
extension=pdo_mysql
  1. 創(chuàng)建一個(gè)名為config.php的文件,其中包含數(shù)據(jù)庫(kù)連接信息:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";
?>
  1. 創(chuàng)建一個(gè)名為connect.php的文件,用于連接到數(shù)據(jù)庫(kù):
<?php
require_once "config.php";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>
  1. 創(chuàng)建一個(gè)名為query.php的文件,用于執(zhí)行查詢(xún):
<?php
require_once "connect.php";

try {
    $sql = "SELECT id, name FROM your_table_name";
    $result = $conn->query($sql);

    while ($row = $result->fetch()) {
        echo "id: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}

$conn = null;
?>

現(xiàn)在,當(dāng)你運(yùn)行query.php文件時(shí),它將連接到數(shù)據(jù)庫(kù),執(zhí)行查詢(xún)并顯示結(jié)果。請(qǐng)確保將config.php中的數(shù)據(jù)庫(kù)連接信息更改為實(shí)際值,并將query.php中的表名更改為實(shí)際表名。

0