在PHP中,可以使用PHP Data Objects (PDO) 或 MySQLi擴(kuò)展來(lái)連接和操作數(shù)據(jù)庫(kù)。這里是一個(gè)簡(jiǎn)單的示例,展示了如何使用PDO連接到MySQL數(shù)據(jù)庫(kù)并執(zhí)行查詢(xún)。
extension=pdo_mysql
config.php
的文件,其中包含數(shù)據(jù)庫(kù)連接信息:<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";
?>
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();
}
?>
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í)際表名。