PHP后臺框架通常使用PDO(PHP Data Objects)或者MySQLi(MySQL Improved)這兩種方式來連接數據庫。
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
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();
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
這兩種連接方式都可以用來連接MySQL數據庫,但PDO更加靈活和方便,支持多種數據庫類型,而MySQLi只支持MySQL數據庫。在實際開發中,可以根據具體需求來選擇適合自己項目的數據庫連接方式。