要連接MySQL數據庫并獲取數據,你可以使用PHP中的mysqli擴展或PDO擴展。下面是一個示例代碼,演示如何連接MySQL數據庫并獲取數據:
// 連接數據庫
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接是否成功
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 查詢數據
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// 輸出查詢結果
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// 關閉連接
$conn->close();
// 連接數據庫
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 查詢數據
$stmt = $conn->prepare("SELECT * FROM table_name");
$stmt->execute();
// 輸出查詢結果
$result = $stmt->fetchAll();
foreach($result as $row) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// 關閉連接
$conn = null;
以上是使用mysqli擴展和PDO擴展連接MySQL數據庫并獲取數據的示例代碼。你可以根據自己的實際情況選擇其中一種來使用。