【问题标题】:PHP OOP, MYSQLi QueryPHP OOP、MYSQLi 查询
【发布时间】:2015-05-05 12:59:33
【问题描述】:

我为数据库查询创建了一个名为“Connection”的类:

class Connection{
 public $mysqli;

 public function read($query){  
  $result= $this->mysqli->query($query);

  $num_result=$result->num_rows;

  if($num_result>0){
   while($rows=$result->fetch_assoc()){

    $this->data[]=$rows;
  }          
   return $this->data;
  }
 }
}

我是这样称呼我的班级的:

$obj=new Connection("localhost","root","","testpaginate");

$query="SELECT * FROM paginate";
$result=$obj->read($query);
mysqli_free_result($result);

$queries="SELECT * FROM paginate where id=1";
$results=$obj->read($queries);
print_r($results);
?>

当我执行时

$query="SELECT * FROM paginate";
$result=$obj->read($query);

它显示了正确的答案。

当我再次执行时

$queries="SELECT * FROM paginate where id=1";
$results=$obj->read($queries);

它显示当前结果和以前的结果

为什么会这样?非常感谢任何帮助。

【问题讨论】:

  • 因为您重复使用 $this->data[] 并将您的数据附加到那里。在填写之前设置$this->data = array();

标签: php oop mysqli


【解决方案1】:

在你的类中声明变量是正确的。

每次使用它们时都应该这样做(如果不用于其他目的):

class Foo {
    private $data;

    public function read()
    {
        $this->data = array();

        //do your stuff here, i.e. in your loop
        while(...)
           $this->data[] = $row;

        return $this->data;
    }
}

您也可能不想关联私有变量:

class Foo {

    public function read()
    {
        $data = array();

        //do your stuff here, i.e. in your loop
        while(...)
           $data[] = $row;

        return $data;
    }
}

现在$data 只是一个局部变量。

【讨论】:

    【解决方案2】:

    问题是您每次调用read 时都会附加到$this->data。您需要在方法中重新初始化数组$this->data

    if($num_result>0){
        $this->data = array();
        while($rows=$result->fetch_assoc()){
            $this->data[]=$rows;
        }
    }
    

    【讨论】:

      【解决方案3】:

      我认为你不应该在 $this->data 之后使用 []。这意味着它将向数组中添加行。

      【讨论】:

      • 抱歉,这是错误的,现在该属性将只包含查询的最后一行。
      猜你喜欢
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多