Singleton数据库类:删除旧的查询结果

时间:2013-04-01 03:57:28

标签: php mysqli

我为PHP创建了一个单例数据库类。我认为它工作得很好,但事实并非如此。我现在正在制作一个有3个查询的页面。 1检查相册是否存在,1检查用户是否拥有相册,另一个获取相册中的照片。

现在在我的第三个查询中我填充了一个对象,但是前两个查询的结果也在该数组中,所以我得到了通知!

以下是一个例子:

Array
(
[0] => Array
    (
        [id] => 2
        [name] => My new album 1
        [slug] => my-new-album-1
        [user_id] => 1
        [views] => 0
        [datecreated] => 2013/03/23 16:00:43
    )

[1] => Array
    (
        [id] => 3
        [name] => My new album 1
        [slug] => my-new-album-1
        [user_id] => 1
        [views] => 0
        [datecreated] => 2013/03/23 23:51:58
    )

[2] => Array
    (
        [id] => 2
    )

[3] => Array
    (
        [id] => 117
        [title] => 
        [location_id] => 
        [date] => 2013-03-30 00:42:26
        [user_id] => 1
        [album_id] => 2
    )

这就是我如何进行查询并返回数组:

mysqli_conn::getInstance()->query($sql)->all_assoc()

这是我的数据库类的一部分,它执行查询并返回结果:

public function query( $sql ){

 $starttime = $this->time_to_float();        
 $this->query = mysqli_query($this->connection, $sql);          
 $endtime = $this->time_to_float();
 $exectime = ($endtime - $starttime);


 if (!$this->query){        
    throw new Exception(mysqli_error($this->connection));        
 } else {

    $this->arQueryLog[] = array ( 'query' => $sql, 
                                  'exectime' => $exectime, 
                                  'affected_rows' => mysqli_affected_rows($this->connection),
                                  'last_insert_id' => $this->lastID() );                                      


 }

 return $this;

}

public function all_assoc ()
{
    while($result = mysqli_fetch_assoc($this->query)){
        $this->result[] = $result;
    }

    return $this->result;

}

怎么会这样只有最后一个查询结果在结果数组中?

谢谢!

3 个答案:

答案 0 :(得分:0)

您正在将结果推送到类的result属性。由于它是一个singelton,之前的值保留在result属性中,每次调用all_assoc()方法时,新结果都会被推送到属性中。

在推送新结果之前,您应该在all_assoc()方法中取消设置result属性。

答案 1 :(得分:0)

与数据库类无关的2个主要错误

  • 每个变量在使用前都必须初始化。这段代码失败了。
  • 如果您使用本地变量作为本地数据,PHP甚至可以原谅上述错误

所以,正确的代码必须是

public function all_assoc ()
{
   $result = array(); //initializing a local variable 
   while($result = mysqli_fetch_assoc($this->query)){
        $result[] = $result;
    }
    return $result;
}

这个all_assoc函数最好用$ result变量来代替,而不是使用类属性。

与数据库类相关的1个主要错误。

  • 您没有使用占位符,因此,您的查询容易受到SQL注入攻击。

所以,因为你已经开始上课了,所以看看SafeMysql。它将使您的代码更短,更安全。

答案 2 :(得分:0)

我认为@Jueecy可能对设计有一个有效的观点,但由于我们无法访问您的完整实现,让我们使用我们的工作。

虽然将数据库连接存储在单例中是有意义的,但将查询结果存储在单例(当然不是数据库连接单例)中并不合适,因为您很可能会有多个查询根据要求。

从您分享的代码中,我最好的建议是直接返回$query值(不将其存储在$ this上),并让all_assoc()(及相关函数)接受{{ 1}}并直接返回$query(不将其存储在$ this上)。

如果需要提供自定义逻辑(也就是$result和{,则可以创建一个Query类来包装$query和一个Result类来包装单个结果集您的exectime函数中的{1}}逻辑,但您尚未提供任何显示必要的代码。

祝你好运,

-David Farrell