MYSQLi_Query无法使用包含文件夹中的数据库连接

时间:2011-09-09 17:29:50

标签: php mysqli

我在文档根目录之外的includes文件夹中设置了dbconn.php文件。当我从它引用$ mysqli作为select语句的一部分时,我收到错误

Warning: mysqli_query() [function.mysqli-query]: Couldn't fetch mysqli     
in /home/tgitcorp/public_html/Admin/admin_index.php on line 18
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given 
in /home/tgitcorp/public_html/Admin/admin_index.php on line 20 

我的dbconn.php如下:

<?php
    $mysqli = new mysqli('localhost','dbuser','pass','dbname');
    if ($mysqli->connect_error){
        die('Connect Error (' . $mysqli_connect_errno . ')'. $mysqli->connect_error);
    }
    $mysqli->close();   
?>

这是我的代码:

<?php 
include_once '/home/tgitcorp/includes/dbconn.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML     
1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Tricorp Job Listing Admin Panel</title>
    <link rel="stylesheet" href="../css/style.css" type="text/css"/>
</head>
<body>
    <h1>Job Listing Administration</h1>
    <h2>Step 1:  Please Select Your Restaurant</h2>
    <form id="frmSelStore" method="post">
    <?php 
    $result=mysqli_query($mysqli,'SELECT location from restaurant');
    echo '<select name="ddlStore">';
    while($row=mysqli_fetch_array($result))
    {
        echo '<option value="' . htmlspecialchars($row['location']) . '"></option>';
    }
    echo '</select>';
    ?>
    </form>
</body>
</html>

我想查询餐馆餐桌以检索位置字段,并在我的下拉框中将该字段填充为值。任何人都可以协助解决此错误吗?

谢谢!

更新#2:修改后的代码块:

<?php 
$result=$mysqli->query($mysqli,'SELECT location from restaurant');
echo '<select name="ddlStore">';
while($row=$mysqli->query($result))
{
    echo '<option value="' . htmlspecialchars($row['location']) . '">';
    '</option>';
}
echo '</select>';
?>

产生错误消息:

Warning: mysqli::query() expects parameter 1 to be string, object given 
in /home/tgitcorp/public_html/Admin/admin_index.php on line 18
Warning: mysqli::query() [mysqli.query]: Empty query 
in /home/tgitcorp/public_html/Admin/admin_index.php on line 20 

1 个答案:

答案 0 :(得分:4)

为什么在实例化后立即关闭连接?它必须与此有关。听我说$mysqli->close()属于if区块。

编辑:在任何情况下,关闭连接都是可选的,如下所述:http://php.about.com/od/phpfunctions/qt/mysql_close.htm