從一般網頁連接SQL伺服器,必須使用PHP程式編程。
只要把原來的 html 檔案另存新檔成 PHP 副檔名及上存在一個支援 PHP 的網伺服器上便可。
網伺服器上的 PHP 解譯器可翻譯一般 html,若見到有 <? .... ?> 字樣,則進行該段程式碼。
在你的 PHP 檔中加入 <?=date("d/m/Y h:i:sa") ?> 便會顯示時間。
如果顯示正確,則你的網伺服器是支援 PHP。
在你的網頁中加入以下 PHP 程序
<?
global $db;
$db = new mysqli("IP / localhost", "用戶名稱", "密碼", "數據庫名稱");
if($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
?>
把以上程式複製到檔案中的最首位置。
<?
if(isset($db)) {
$db->close(); //mysqli_close($dbLink);
}
?>
把以上程式複製到檔案中的最尾位置。
IP / localhost:輸入你SQL伺服器的 IP 位址,如果你的網伺服器及SQL伺服器於同一部主機,可輸入 localhost。
用戶名稱:你登入數據庫的名稱
密碼:你登入數據庫的密碼
數據庫名稱:你在數據庫介面中左邊的數據庫名稱,並不是資料表名稱
A. 從數據庫中取出多欄的數據
<?
global $db;
$query = $db->prepare("select uid, username, class, classno from student");
$query->execute();
$users = $query->get_result();
while ($user = $users->fetch_object()) {
$uid = $user->uid;
$username = $user->username;
$class = $user->class;
$classno = $user->classno;
}
?>
B. 取得搜尋結果的數量
<?
global $db;
$query = $db->prepare("select uid, username, class, classno from student");
$query->execute();
$query->store_result();
if ($query->num_rows > 0) {
// User existed
header("Location: http://user_existing", true, 301);
$query->close();
}
else {
// No such user
header("Location: http://no_such_user", true, 301);
}
?>