Using an ojbect of mysqli as static & as a member
Posted: Fri Feb 29, 2008 9:02 am
Im using a mysqli object ($mysqli) inside a class cls.
When creating an instance of cls, I dont want the mysqli object to create a connection to the database for each instance.
So I made $mysqli static.
This is fine since this is a once-off thing to get the result in a non-static variable
$this->result = self::mysqli->query($query));
Problem is, when using multi_query(), the result set is stored as
$this->result = self::mysqli->store_result();
After all rows are returned for the current set, I got to get the next result-set: self::mysqli->next_result();
This is where static $mysqli is a bad idea, because it can conflict with another object of cls.
So declaring $mysqli as non-static seems to be the only way.
But what if I do this ...
I use static $mysqli to make the connection - which is a one time thing - will call in the beginning.
Now, for each instance of cls, I copy the static $mysqli to a member $mysqli2.
Does this line ($this->mysqli2 = self::$mysqli;) actually help is reducing db connections ?
Thanks
When creating an instance of cls, I dont want the mysqli object to create a connection to the database for each instance.
So I made $mysqli static.
This is fine since this is a once-off thing to get the result in a non-static variable
$this->result = self::mysqli->query($query));
Problem is, when using multi_query(), the result set is stored as
$this->result = self::mysqli->store_result();
After all rows are returned for the current set, I got to get the next result-set: self::mysqli->next_result();
This is where static $mysqli is a bad idea, because it can conflict with another object of cls.
Code: Select all
class cls
{
private static $mysqli;
private $result = FALSE;
private $result_set_no = 0;
public function __construct()
{
}
public static function connectdb()
{
self::$mysqli = new mysqli("localhost", "username", "password", "database-name");
if (mysqli_connect_errno())
{
echo "Connect failed: ".mysqli_connect_error();
return FALSE;
}
}
public function query($sql) # $sql = $sql1.$sql2.$sql3;
{
if (!$mysqli->multi_query($sql))
return FALSE;
}
public function next()
{
if (!this->$result)
{
$this->result = $mysqli->store_result();
$this->result_set_no++;
}
if ($this->result)
$row = $this->result->fetch_assoc();
if ($row == NULL)
{
if (self::mysqli->more_results())
{
$this->result = FALSE;
self::mysqli->next_result();
return self::next();
}
}
else
return FALSE;
return array($this->result_set_no, $row);
}
}But what if I do this ...
Code: Select all
private static $mysqli;
private $mysqli2;
public function __construct()
{
$this->mysqli2 = self::$mysqli; # Avoid connecting to the database again - just copy resource
}
Now, for each instance of cls, I copy the static $mysqli to a member $mysqli2.
Does this line ($this->mysqli2 = self::$mysqli;) actually help is reducing db connections ?
Thanks