我想將以下腳本從mysql轉換爲mysqli,但遇到問題。將腳本從mysql轉換爲mysqli
這是原單腳本用mysql:
//database connection
$dbname = 'nursery';
$link = mysql_connect("localhost","root","") or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $link) or die("Couldn't select database");
?>
<div style="width:728px;margin:auto;">
<div id='cssmenu'>
<ul>
<?php
function query($parentid) { //function to run a query
$query = mysql_query ("SELECT * FROM menu WHERE parentid=$parentid");
return $query;
}
function has_child($query) { //This function checks if the menus has childs or not
$rows = mysql_num_rows ($query);
if ($rows > 0) {
return true;
} else {
return false;
}
}
function fetch_menu($query) {
while ($result = mysql_fetch_array ($query)) {
$menu_id = $result ['id'];
$title = $result ['title'];
$url = $result ['url'];
echo "<li class='has-sub '><a href='{$url}'><span>{$title}</span></a>";
if (has_child (query ($menu_id))) {
echo "<ul>";
fetch_menu (query ($menu_id));
echo "</ul>";
}
echo "</li>";
}
}
fetch_menu (query(0)); //call this function with 0 parent id
?>
</ul>
</div>
</div>
所以我試圖將其轉換成我的網站的其餘部分使用和到目前爲止,這已經得到的mysqli:
<?php
require("../login/common.php");
//database connection;
include '../connect.php';
?>
<div style="width:728px;margin:auto;">
<div id='cssmenu'>
<ul>
<?php
function query($parentid) { //function to run a query
$query = mysqli_query ($db, "SELECT * FROM menu WHERE parentid=$parentid");
return $query;
}
function has_child($query) { //This function checks if the menus has childs or not
$rows = mysqli_num_rows ($query);
if ($rows > 0) {
return true;
} else {
return false;
}
}
function fetch_menu($query) {
while ($result = mysqli_fetch_array ($query)) {
$menu_id = $result ['id'];
$title = $result ['title'];
$url = $result ['url'];
echo "<li class='has-sub '><a href='{$url}'><span>{$title}</span></a>";
if (has_child (query ($menu_id))) {
echo "<ul>";
fetch_menu (query ($menu_id));
echo "</ul>";
}
echo "</li>";
}
}
fetch_menu (query(0)); //call this function with 0 parent id
?>
</ul>
</div>
</div>
問題是我得到各種錯誤,我不完全確定爲什麼,我知道數據庫錯誤可能下降到$ db沒有被傳遞到函數,但即使我寫函數fetch_menu($查詢,$ db){我仍然有同樣的錯誤?
Notice: Undefined variable: db in C:\easyphpserver\data\localweb\projects\nursery\menu\menu3.php on line 147
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\easyphpserver\data\localweb\projects\nursery\menu\menu3.php on line 147
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\easyphpserver\data\localweb\projects\nursery\menu\menu3.php on line 159
connect.php的內容是:
<?php
$db = new mysqli('localhost', 'root', '', 'nursery');
$db->set_charset('utf8mb4');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
?>
這'$鏈接=的mysql_connect( 「localhost」 的 「根」, 「」)'不會恰好是你的'connect.php'文件中,不是嗎? –
連接的內容是 –
您的連接也需要'mysqli_'這就是問題所在。 'mysql_'和'mysqli_'函數不會混合。 –