开发者

MYSQLi_Query not working with DB Connection in Includes Folder

I've setup a dbconn.php file in the includes folder outside of the document root. When I reference $mysqli from it as part of the select statement, I receive an error

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 

My dbconn.php is as follows:

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

Here's my code:

<?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>

I want to query the restaurant table to retrieve the location field and populate that field as values in my dropdown box. Can anyone assist in resolving this error?

Thanks!

UPDATE #2: Revised code block:

<?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>';
?>

yields the error message:

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 


Why do you close the connection as soon as you instantiate it? It must have something to do with that. Sounds to me that $mysqli->close() belongs inside the if block.

EDIT: In any case, closing the connection is optional, as described here: http://php.about.com/od/phpfunctions/qt/mysql_close.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜