如何解决此警告:mysqli_fetch_assoc() 期望参数 1 为 mysqli_result,如何解决此问题
How to Solve this Warning: mysqli_fetch_assoc() expect s parameter 1 to be mysqli_result, How to solve this
在下面的代码中,它会在执行时产生警告。警告:mysqli_fetch_assoc() 期望 s 参数 1 为 mysqli_result,如何解决?
<?php
require '../smarty3/libs/Smarty.class.php';
$smarty = new Smarty;
class conn
{
public $conn = '';
public function fetchAll()
{
$sql = "SELECT * FROM test" ;
if(mysqli_query($this->conn,$sql))
{ return 'success'; }
else{ return 'error'; }
}
}
$db = new conn();
$record = $db->fetchAll();
if($record != 'error'){
while($row = mysqli_fetch_assoc($record))
{
header('location : view.tpl');
}
}else{ echo "No Records Found";}
$smarty->display('view.tpl');
?>
**View.tpl**
<table align = "center">
{section name = i loop = $row}
<tr> <td> {$smarty.section.i.rownum} </td>
<td> {$row[i].name} </td>
<td> {$row[i].country} </td>
</tr>
{/section}
</table>
谢谢大家的回答。
这是因为 $record = $db->fetchAll()
是 return 字符串(success
或 error
)而不是 mysql 资源。
考虑将 Conn Class 更改为:
class conn
{
public $conn = '';
public function fetchAll()
{
$sql = "SELECT * FROM test" ;
$r = mysqli_query($this->conn,$sql)
if($r)
{
return $r; }
else{ return 'error'; }
}
}
现在 fetchAll()
方法将 return 一个 mysqli_result
一个成功的查询,或者 'error'
如果不是
在我看来,这不是处理错误的最佳方式。考虑研究 try/catch 块以及如何从 class 堆栈中 "throw" 错误。
在下面的代码中,它会在执行时产生警告。警告:mysqli_fetch_assoc() 期望 s 参数 1 为 mysqli_result,如何解决?
<?php
require '../smarty3/libs/Smarty.class.php';
$smarty = new Smarty;
class conn
{
public $conn = '';
public function fetchAll()
{
$sql = "SELECT * FROM test" ;
if(mysqli_query($this->conn,$sql))
{ return 'success'; }
else{ return 'error'; }
}
}
$db = new conn();
$record = $db->fetchAll();
if($record != 'error'){
while($row = mysqli_fetch_assoc($record))
{
header('location : view.tpl');
}
}else{ echo "No Records Found";}
$smarty->display('view.tpl');
?>
**View.tpl**
<table align = "center">
{section name = i loop = $row}
<tr> <td> {$smarty.section.i.rownum} </td>
<td> {$row[i].name} </td>
<td> {$row[i].country} </td>
</tr>
{/section}
</table>
谢谢大家的回答。
这是因为 $record = $db->fetchAll()
是 return 字符串(success
或 error
)而不是 mysql 资源。
考虑将 Conn Class 更改为:
class conn
{
public $conn = '';
public function fetchAll()
{
$sql = "SELECT * FROM test" ;
$r = mysqli_query($this->conn,$sql)
if($r)
{
return $r; }
else{ return 'error'; }
}
}
现在 fetchAll()
方法将 return 一个 mysqli_result
一个成功的查询,或者 'error'
如果不是
在我看来,这不是处理错误的最佳方式。考虑研究 try/catch 块以及如何从 class 堆栈中 "throw" 错误。