我正在编写用户定义的函数来执行sql查询。 通常我必须编写try catch块,无论我在编写sql语句。 我想写一个函数并将查询传递给该函数并编写try catch块并从该函数返回结果,而不是这样做。我想在该功能中做的只是
如果查询成功执行,则
一个。对非选择查询返回true
湾如果是选择查询,则返回已提取的行
我能够返回成功或查询执行失败但是在使用select传递给函数时我被困住了。有人可以为此建议解决方法。
这是伪代码
function oxeDbQueryExecute($query, $dbObject){
$returnValue = false;
try{
$resultSetObject = $dbObject->query($query);
if($resultSetObject){ // query executed successfully
$returnValue = true;
if(selectquery){ // if pdo statement contains any rows because of the executed query is a select query
$returnValue = an array containg all the rows
}
}
}catch(PDOException $exception){
error_log($exception->getMessage());
}
return $returnValue;
}
答案 0 :(得分:0)
// defining function
function oxeDbQueryExecute($query, $dbObject){
$returnValue = false;
try{
$resultSetObject = $dbObject->query($query);
if($resultSetObject){ // checking query executed successfully or not
$returnValue = true;
/*
** checking result set is having any records or not.
** Result set will have rows if the query is "select" type query.
** In this case return array consisting rows in the format of objects
*/
$rowOfObjects = $resultSetObject->fetchAll(PDO::FETCH_OBJ);
if(count($rowOfObjects)){
$returnValue = $rowOfObjects;
}
}
}catch(PDOException $exception){
error_log($exception->getMessage()." Query : ".$query."");
}
return $returnValue;
}
// creating databse connection
$db = new PDO("sqlite:D:/****/****/300/******_*_En/Query_ImageAnno.data");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // to make thorw exceptions instead of fatal error
$queryResult = oxeDbQueryExecute("insert into chapter('tfoken')values('dfdf')", $db);
if($queryResult){
if(count($queryResult)){ // if executed query is select type query
print_r($queryResult);
}
}else{
echo "failed";
}