如果我在课堂上执行 sql 查询可以吗?因为我确实想在执行查询时一直使用 DRY 格式来使用执行准备获取。在谈论 PHP 的性能和速度时可以吗?
class foo{
protected function dbConnect()
{
$con="mysql:host=yourhost;dbname=yourdbname";
try{
$conn=new PDO($con, "user", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOexception $e)
{
die ("error: ".$e->getMessage());
}
return $conn;
}
public function selectQuery($query,$fieldsvalues,$type)
{
$executequery=$this->dbConnect()->prepare($query);
$executequery->execute($fieldsvalues);
if($type=='fetchColumn()')
{
return $queryexecute->fetchColumn();
}
if($type=='fetch()')
{
return $queryexecute->fetch();
}
if($type=='fetchAll()')
{
return $queryexecute->fetchAll();
}
}
public function otherQuery($query,$fieldsvalues)
{
$queryexecute=$this->dbConnect()->prepare($query);
$queryexecute->execute($fieldsvalues);
return $queryexecute->rowCount();
}
}
$newquery=new foo();
$newquery->selectQuery("SELECT foo from bar where foobar='?'",array('baz'),'fetchColumn()');