我在数据库类中使用以下代码来运行PHP应用程序的其余部分的查询:
public function query($sql, $parameters = [])
{
try
{
$this->setError(false);
$stmt = $this->getPdo()->prepare($sql); //assign to a variable with a short name
if ($stmt):
$x = 1;
if (count($parameters)):
foreach($parameters as $parameter):
$stmt->bindValue($x, $parameter);
$x++;
endforeach;
endif;
$stmt->execute();
$this->setResults($stmt->fetchAll(PDO::FETCH_OBJ));
$this->setCount($stmt->rowCount());
endif;
return $this;
}
catch(PDOException $e)
{
$this->setError(true);
throw $e;
}
}
似乎只能查找SELECT查询。但是,当涉及INSERT,UPDATE或DELETE的SQL语句使用它时,此方法可以正常工作(因为它会对数据库中的数据执行操作),但它会显示一个致命错误,引用未捕获的异常“PDOException”,并显示消息 SQLSTATE [IMSSP]:查询的活动结果不包含任何字段。它表示此行引发异常:
$this->setResults($stmt->fetchAll(PDO::FETCH_OBJ));
是否可以修改上述代码以确定execute()是执行SELECT还是INSERT / UPDATE / DELETE而只执行SELECT语句的fetchAll()?
注意:MS SQL Server中使用的数据库
答案 0 :(得分:-1)
想出来:
public function query($sql, $parameters = [])
{
try
{
$this->setError(false);
$stmt = $this->getPdo()->prepare($sql); //assign to a variable with a short name
if ($stmt):
$x = 1;
if (count($parameters)):
foreach($parameters as $parameter):
$stmt->bindValue($x, $parameter);
$x++;
endforeach;
endif;
$stmt->execute();
$this->setCount($stmt->rowCount()); //for INSERT, UPDATE, DELETE stmts this is number of rows that were affected, displays -1 for SELECT stmt
if ($stmt->rowCount() == -1): //conditionally do the following if SQL stmt was a SELECT
$this->setResults($stmt->fetchAll(PDO::FETCH_OBJ));
$this->setCount($stmt->rowCount()); //overwrite count attribute with number of rows returned by SELECT stmt
endif;
endif;
return $this;
}
catch(PDOException $e)
{
$this->setError(true);
throw $e;
}
}