Can anyone help me solve this? I having this line code with error of
PHP Fatal error: Call to a member function fetch_assoc() on string in C:\inetpub\wwwroot\dbcontroller.php on line 26
Line 26 is this line of code: $result = $query->fetch_assoc();
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = " ";
private $database = "test";
function __construct() {
$conn = $this->connectDB();
if(!empty($conn)) {
$this->selectDB($conn);
}
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password);
return $conn;
}
function selectDB($conn) {
mysqli_select_db($conn,$this->database);
}
function runQuery($query) {
$result = $query->fetch_assoc();
// $result = mysqli_query($query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
}
?>
答案 0 :(得分:0)
您必须取消注释代码行 -
$result = mysqli_query($query);
并评论此行 -
$result = $query->fetch_assoc();
没有收到此错误。
答案 1 :(得分:0)
错误非常明显。你不能在字符串中调用函数,例如
// Wrong
$name = 'Johnny';
echo $name->foo();
在你的情况下:
function runQuery($query) {
$result = $query->fetch_assoc();
// [...]
}
...你没有说$query
包含什么,但是上下文建议是带有SQL代码的字符串。简单来说,现在是如何使用mysqli扩展。请随意查看the manual并查看一些usage examples。
答案 2 :(得分:0)
我认为你错过了对此的争论。
$result = mysqli_query($conn, $query);
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
答案 3 :(得分:0)
I changed your code, Now try.
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = " ";
private $database = "test";
function __construct() {
$conn = $this->connectDB();
if(!empty($conn)) {
$this->selectDB($conn);
}
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password);
return $conn;
}
function selectDB($conn) {
mysqli_select_db($conn,$this->database);
}
function runQuery($query) {
$result = mysqli_query($query);
while($row= $result->fetch_assoc()) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
}
?>