PHP MySQL 數(shù)據(jù)庫(kù)連接是網(wǎng)站開(kāi)發(fā)過(guò)程中常用的一種技術(shù),可以用來(lái)將數(shù)據(jù)存儲(chǔ)在 MySQL 數(shù)據(jù)庫(kù)中并進(jìn)行訪問(wèn)。在 PHP 中,可以通過(guò) MySQLi 和 PDO 兩種方式進(jìn)行數(shù)據(jù)庫(kù)連接。
MySQLi 可以說(shuō)是 MySQL 擴(kuò)展庫(kù)的升級(jí)版,常見(jiàn)的方法有 mysqli_connect()、mysqli_query() 等。其中,mysqli_connect() 實(shí)現(xiàn)了與 MySQL 數(shù)據(jù)庫(kù)建立連接的功能,以下是一個(gè)連接代碼示例:
<?php $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; // 創(chuàng)建連接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 檢測(cè)連接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; ?>
PDO 是 PHP Data Objects 的簡(jiǎn)稱(chēng),是一種數(shù)據(jù)庫(kù)訪問(wèn)方法,可以讓 PHP 數(shù)據(jù)庫(kù)訪問(wèn)更加規(guī)范化,在操作方面也更加靈活,其常見(jiàn)的方法有 PDO::__construct()、PDO::query() 等。以下是一個(gè) PDO 連接 MySQL 數(shù)據(jù)庫(kù)的代碼示例:
<?php $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 設(shè)置 PDO 錯(cuò)誤模式為異常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
在實(shí)際應(yīng)用中,除了連接數(shù)據(jù)庫(kù)外,我們還需要進(jìn)行數(shù)據(jù)的增刪改查等操作,下面以 MySQLi 增刪改查為例進(jìn)行說(shuō)明:
增加數(shù)據(jù):
<?php $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "
" . mysqli_error($conn); } ?>
刪除數(shù)據(jù):
<?php $sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } ?>
修改數(shù)據(jù):
<?php $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); } ?>
查詢(xún)數(shù)據(jù):
<?php $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) >0) { // 輸出數(shù)據(jù) while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 results"; } ?>
總的來(lái)說(shuō),PHP MySQL 數(shù)據(jù)庫(kù)連接是一個(gè)非常實(shí)用的技術(shù),它為網(wǎng)站開(kāi)發(fā)帶來(lái)了極大的方便和效率。以上是針對(duì)兩種連接方式的簡(jiǎn)單介紹和對(duì)增刪改查功能的實(shí)現(xiàn),相信讀者對(duì)該技術(shù)已經(jīng)有了初步的了解。