PHP后台框架通常使用PDO(PHP Data Objects)或者MySQLi(MySQL Improved)这两种方式来连接数据库。
- PDO连接方式:
$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(); }
- MySQLi连接方式:
$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数据库。在实际开发中,可以根据具体需求来选择适合自己项目的数据库连接方式。