未定义的变量:con无法从mysql获取数据

时间:2015-12-05 06:56:12

标签: php mysqli

的index.php

<?php include'includes/nav.php'; ?>
<?php include "includes/db.php"; ?>

包括/ nav.php

<?php 
$allcategeories = mysqli_query($con,"SELECT * FROM categories");
while($row = mysqli_fetch_assoc($allcategeories ))
{
   echo "<li>{$row['cat_title']}</li>";
}
 ?>

包括/ db.php中

<?php
$db['DBhost'] = "localhost";
$db['DBuser'] = "root";
$db['DBpass'] = "";
$db['DBNAME'] = "cms";
foreach($db as $key => $value) {
    define(strtoupper($key), $value);
}
$con = mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
if(!$con) {
    echo "cannot establish connection";
}
?>

错误

  

注意:未定义的变量:第19行的C:\ xampp \ htdocs \ blog \ includes \ nav.php中的con

     

警告:mysqli_query()要求参数1为mysqli,在第19行的C:\ xampp \ htdocs \ blog \ includes \ nav.php中给出null

     

警告:mysqli_fetch_assoc()要求参数1为mysqli_result,在第20行的C:\ xampp \ htdocs \ blog \ includes \ nav.php中给出null

1 个答案:

答案 0 :(得分:1)

更改 index.php

中包含文件的顺序

首先包含数据库文件

<?php include "includes/db.php"; ?>

然后

<?php include'includes/nav.php'; ?>

因为db.php中包含nav.php之后你的数据库连接存在污染,所以你得到的是不正确变量con