Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用mysql在PHP中循环获取的查询_Php_Mysql - Fatal编程技术网

如何使用mysql在PHP中循环获取的查询

如何使用mysql在PHP中循环获取的查询,php,mysql,Php,Mysql,我有一个PHP类,在该类中初始化从构造函数中的数据库检索的数组: class TableClass{ public function __construct($con, $id){ $this->con = $con; $query = mysqli_query($this->con, "SELECT * FROM table1 WHERE id='$id'"); $this->table_resu

我有一个PHP类,在该类中初始化从构造函数中的数据库检索的数组:

class TableClass{
    public function __construct($con, $id){
        $this->con = $con;            
        $query = mysqli_query($this->con, "SELECT * FROM table1 WHERE id='$id'");
        $this->table_result= mysqli_fetch_array($query);
    }
}
我有不同的函数,我想在不必再次获取的情况下使用数组。我只想循环分析结果并进行一些计算

我尝试了以下语法:

public function getNumberOfComments(){
    for ($i = 0; $i < count($this->table_result); $i++) {
          $comment= $this->table_result[$i]['comment'];                    
    }
}
公共函数getNumberOfComments(){
对于($i=0;$itable_result);$i++){
$comment=$this->table_result[$i]['comment'];
}
}
我得到一个错误:

非法字符串偏移量“注释”


正确的语法是什么?

您正在从结果集中提取一行:

$this->table_result= mysqli_fetch_array($query);
假设
id
是主键,则结果集中将有0或1行,因此如果找到一行,则可以直接访问字段,而无需使用循环:

$comment= $this->table_result['comment']; 

您正在从结果集中提取一行:

$this->table_result= mysqli_fetch_array($query);
假设
id
是主键,则结果集中将有0或1行,因此如果找到一行,则可以直接访问字段,而无需使用循环:

$comment= $this->table_result['comment']; 
非法字符串偏移量“comment”告诉您
$this->table_result[$i]
的值不是数组,因此不包含名为
comment
的元素

问题可能是由于构造函数中的代码无法正常工作引起的;您在那里没有任何错误检查,因此如果失败,它不会告诉您

在构造函数中添加一些错误检查,找出失败的原因,并修复它。

非法字符串偏移量“comment”告诉您
$this->table\u result[$i]
的值不是数组,因此不包含名为
comment
的元素

问题可能是由于构造函数中的代码无法正常工作引起的;您在那里没有任何错误检查,因此如果失败,它不会告诉您


在构造函数中添加一些错误检查,找出它失败的原因,并修复它。

您只从结果集中获取了一行,那么为什么要对循环使用
?简单
$comment=$this->table_结果['comment']
很好。首先尝试打印结果
$this->table\u result
,查看已提取的内容。您只从结果集中提取一行,为什么要使用
进行循环?简单
$comment=$this->table_结果['comment']
就可以了。首先试着打印结果
$this->table\u result
,看看我们两人在同一时间发布了什么内容我很好奇;因为它们是用
$this->con=$con“构造”的
并将2个参数传递给构造函数,
$id
不应该也包含属性吗?@Fred ii-可能是,取决于类的其余部分。从我所看到的来看,即使是
$this->con
都是未使用的/不需要的,但可能在其他方法中……我们两人都在同一时间发布我很好奇;因为它们是用
$this->con=$con“构造”的
并将2个参数传递给构造函数,
$id
不应该也包含属性吗?@Fred ii-可能是,取决于类的其余部分。从我所看到的来看,甚至
$this->con
都是未使用/不需要的,但可能在其他方法中。。。