I've been wondering about this for a few weeks. My code practice is to create several classes (insert, update, delete, etc) and then create functions inside of that.
The problem is that for every function I do something like:
public function clients(){
$db = new mysqli($this->host, $this->user, $this->pass, $this->db);
if ($db->connect_errno) {
printf("Connecting error" . $db->connect_error);
return false;
exit();
}
$db->set_charset("utf8");
$visibile = true;
$query = $db->prepare("SELECT * FROM clients WHERE visible = ?");
$query->bind_param("i", $visible);
$query->execute();
$query->bind_result($id, $name, $address, $photo);
$query->store_result();
$rows = array();
while($query->fetch()){
$rows[] = array("id" => $id, "name" => $name, "address" => $address, "photo" => $photo);
}
$query->close();
$db->close();
return $rows;
}
I've been thinking about reduce this code..at least the connection in the beginning of every function.
// currently call
include_once('select.php');
$select = new select();
$rows = $select->clients();
Something better would be
$select = new select();
$rows = $select->connect()->clients();
Or even better
$rows = $connect->select()->clients();
I know that this is possible, I just don't know how. Or there's even a better approach than this one?