您好我在php文件中有以下代码
global $server, $mysqlusername, $mysqlpassword, $db;
$conn = new mysqli($server, $mysqlusername, $mysqlpassword, $db);
function getCategories() {
global $conn;
$categories = array();
$sql = "SELECT categoryName FROM reportcategorys";
$maincat = $conn->query($sql);
while($row = $maincat->fetch_array(MYSQLI_ASSOC)) {
// do something with the $row
array_push($categories, $row);
}
$sql1 = "SELECT * FROM reportsubcategorys";
$subcats = $conn->query($sql1);
// Loop through sub categories and append to parent array
while($row = $subcats->fetch_array(MYSQLI_ASSOC)) {
$parent = $row['categoryName'];
$name = $row['subCategoryName'];
// Append subcategory name as child to the parent category
for ($i=0; $i<count($categories); $i++) {
if ($categories[$i]['categoryName'] == $parent) {
array_push($categories[$i], $name);
}
}
}
//print_r($categories);
return $categories;
}
它给我一条错误信息
“致命错误:在”
中的非对象上调用成员函数fetch_array()知道可能导致这种情况的原因吗?
由于
答案 0 :(得分:1)
您的查询可能未正确执行。
如果查询未正确执行, mysqli->query()
将返回布尔值FALSE
,否则将返回mysqli_result
个对象。因此,在每次查询之后,在调用fetch_array()方法之前,请检查查询的结果。这样的事情。
$maincat = $conn->query($sql) or die($conn->error);
或
$maincat = $conn->query($sql);
if(!$maincat){
echo $conn->error;
}
此外,当您与数据库建立连接时,请检查连接是否没有错误。
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
答案 1 :(得分:0)
您是否出于任何原因使用fetch_array?
试试这个......
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* verificar la conexión */
if (mysqli_connect_errno()) {
printf("Conexión fallida: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* obtener array asociativo */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* liberar el resultset */
$result->free();
}
/* cerrar la conexión */
$mysqli->close();
?>