編碼的世界 / 優質文選 / 文明

PHP5.5 mysqli如何連接MySQL數據庫和讀取數據


2021年7月05日
-   

在學習 1. 開啟PHP的API支持
(1)首先修改您的php.ini的配置文件。 查找下面的語句: ;extension=php_mysqli.dll 將其修改為: extension=php_mysqli.dll
(2)重新啟動Apache/IIS,即可。
(3)說明:PHP需要單獨的文件來支持這個擴展庫,一般在PHP目錄下的ext目錄裏能找到php_mysqli.dll文件(PHP <= 5.0.2 中是 libmysqli.dll),當然,在PHP的配置文件當中要有正確指向ext的信息(extension_dir)。假若您的PHP沒有這個文件,您可以去下載PHP5的源碼包。另外,這個API擴展,只能在PHP5以上版本使用。其它具體信息,請看下面。
2.PHP mysqli身份證
mysqli是“MySQL, Improved”的縮寫,該擴展僅適用於PHP 5。它能用於MySQL 4.1.1和更高版本。該擴展完全支持MySQL 5.1中采用的鑒定協議,也支持預處理語句和多語句API。此外,該擴展還提供了先進的、面向對象的編程接口
<?php
/* Connect to a MySQL server 連接數據庫服務器 */
$link = mysqli_connect(
'localhost', /* The host to connect to 連接MySQL地址 */
'user', /* The user to connect as 連接MySQL用戶名 */
'password', /* The password to use 連接MySQL密碼 */
'world'); /* The default database to query 連接數據庫名稱*/
if (!$link) {
printf("Can't connect to MySQL Server. Errorcode: %s ", mysqli_connect_error());
exit;
}
/* Send a query to the server 向服務器發送查詢請求*/
if ($result = mysqli_query($link, 'SELECT Name, Population FROM City ORDER BY Population DESC LIMIT 5')) {
//print("Very large cities are: ");
/* Fetch the results of the query 返回查詢的結果 */
while( $row = mysqli_fetch_assoc($result) ){
printf("%s (%s) ", $row['Name'], $row['Population']);
}
/* Destroy the result set and free the memory used for it 結束查詢釋放內存 */
mysqli_free_result($result);
}
/* Close the connection 關閉連接*/
mysqli_close($link);
?>

使用 MySQLi
以下實例中我們從 myDB 數據庫的 MyGuests 表讀取了 id, firstname 和 lastname 列的數據並顯示在頁面上:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 輸出數據
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 結果";
}
$conn->close();
?>

以上代碼解析如下:
首先,我們設置了 SQL 語句從 MyGuests數據表中讀取 id, firstname 和 lastname 三個字段。之後我們使用改 SQL 語句從數據庫中取出結果集並賦給複制給變量 $result。
函數 num_rows() 判斷返回的數據。
如果返回的是多條數據,函數 fetch_assoc() 將結合集放入到關聯數組並循環輸出。 while() 循環出結果集,並輸出 id, firstname 和 lastname 三個字段值。
以下實例使用 MySQLi 面向過程的方式,效果類似以上代碼:
實例 (MySQLi - 面向過程)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 創建連接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("連接失敗: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// 輸出數據
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 結果";
}
mysqli_close($conn);
?>

使用 PDO (+ 預處理)
以下實例使用了預處理語句。
選取了 MyGuests 表中的 id, firstname 和 lastname 字段,並放到 HTML 表格中:
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "
";
}
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
// 設置結果集為關聯數組
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

引用:http://www.runoob.com/php/php-mysql-select.html

熱門文章