mysqli_fetch_array 函式取得資料表 tblphp 中的紀錄,顯示在網頁上。
mysqli_fetch_array 的第 2 個參數 MYSQLI_ASSOC 表示回傳的陣列以欄位名稱為索引。
mysqli_fetch_array($retval, MYSQLI_ASSOC) 也可以直接以函式 mysqli_fetch_assoc($retval) 取代。
mysqli_fetch_array 的第 2 個參數改為 MYSQLI_NUM 則會以數字從 0 開始為索引值。
mysqli_free_result($retval); 釋放記憶體。
[root@kvm3 html]# vim selectrecord.php
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '123qwe';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass)
or die(mysqli_connect_error().PHP_EOL);
mysqli_select_db( $conn, 'dywphp' )
or die('Error: '.mysqli_error($conn).PHP_EOL);
$sql = "select id, title, author,submission_date from tblphp";
$retval = mysqli_query( $conn, $sql )
or die('Error: '.mysqli_error($conn).PHP_EOL);
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo "Dywphp ID: {$row['id']} <br> ".
"Title: {$row['title']} <br> ".
"Author: {$row['author']} <br> ".
"Submission Date: {$row['submission_date']} <br> ".
"--------------------------------<br>";
}
mysqli_free_result($retval);
echo "Fetched data successfully\n";
mysqli_close($conn);
?>
http://kvm3/selectrecord.php,管線處理將 html 換行標籤 <br> 改成 shell 的換行符號 \n,網頁上列出資料表 tblphp 中的紀錄。
[root@kvm3 html]# curl -s http://kvm3/selectrecord.php | sed 's/<br> */\n/g' Dywphp ID: 1 Title: PHP Author: David Submission Date: 2023-04-13 -------------------------------- Dywphp ID: 2 Title: Mariadb Author: dywang Submission Date: 2023-04-20 -------------------------------- Fetched data successfully
$sql 加入 where 條件,存成 selectwhererecord.php。
[root@kvm3 html]# vim selectwhererecord.php [root@kvm3 html]# grep ^\$sql selectwhererecord.php $sql = "select id, title, author,submission_date from tblphp where author='dywang'";
http://kvm3/selectwhererecord.php,管線處理將 html 換行標籤 <br> 改成 shell 的換行符號 \n。
網頁只列出資料表 tblphp 中 author='dywang' 的紀錄。
[root@kvm3 html]# curl -s http://kvm3/selectwhererecord.php | sed 's/<br> */\n/g' Dywphp ID: 2 Title: Mariadb Author: dywang Submission Date: 2023-04-20 -------------------------------- Fetched data successfully
$sql,where 條件改成 like,並存成 selectlikerecord.php。
[root@kvm3 html]# vim selectlikerecord.php [root@kvm3 html]# grep ^\$sql selectlikerecord.php $sql = "select id, title, author,submission_date from tblphp where author like 'd%'";
http://kvm3/selectlikerecord.php,管線處理將 html 換行標籤 <br> 改成 shell 的換行符號 \n。
網頁只列出資料表 tblphp 中 author 開頭是 d 的紀錄,有 David 及 dywang 兩筆。
[root@kvm3 html]# curl -s http://kvm3/selectlikerecord.php | sed 's/<br> */\n/g' [root@kvm3 html]# curl -s http://kvm3/selectlikerecord.php | sed 's/<br> */\n/g' Dywphp ID: 1 Title: PHP Author: David Submission Date: 2023-04-13 -------------------------------- Dywphp ID: 2 Title: Mariadb Author: dywang Submission Date: 2023-04-20 -------------------------------- Fetched data successfully