[英]PHP Using PDO and PDOStatement
I have the following class that takes care of the database interaction: 我有以下类来处理数据库交互:
class DBH {
private $dbh;
public function __construct() {
$this->dbh = new PDO("mysql:host=localhost;dbname=*", "*", "*");
}
public function query($query, $values) {
if (!is_array($values)) {
$values = array($values);
}
$statement = $this->dbh->prepare($query);
$i = 1;
foreach ($values as $value) {
$statement->bindParam($i++, $value);
}
$statement->execute();
return $statement;
}
public function num_rows($query, $values) {
$statement = $this->query($query, $values);
return $statement->rowCount();
}
public function insert($table, $keyvaluepairs) {
$sql = "INSERT INTO `{$table}` (";
$values_sql = ") VALUES(";
$values = array();
foreach ($keyvaluepairs as $key => $value) {
$sql .= "`${key}`, ";
$values_sql .= "?, ";
$values[] = $value;
}
$query = substr($sql, 0, -2).substr($values_sql, 0, -2).")";
return $this->query($query, $values);
}
public function close() {
$this->dbh = null;
}
}
Now I call the following: 现在我打电话给以下人:
$insert_statement = $dbh->insert("users", array(
"email" => $email,
"password" => $password,
"ingame" => $ingame,
"kiosk" => $kiosk
));
Is there a way to check if the $insert_statement
was succesful? 有没有办法检查
$insert_statement
是否成功?
I know that $statement->execute();
我知道
$statement->execute();
returns true
or false
upon execution, however I am returning the whole $statement
. 执行时返回
true
或false
,但是我返回整个$statement
。
If it is possible I'd like to use $statement
to check whether the last execute()
was succesful. 如果有可能我想使用
$statement
检查最后一次execute()
是否成功。
Else there is of course still the possibility to the query status caching in my DBH
class. 否则,我的
DBH
类中仍然存在查询状态缓存的可能性。
You could return a tuple containing both the $statement
, and the boolean with execute()
result. 您可以返回包含
$statement
的元组和包含execute()
结果的布尔值。 Or better yet: throw an exception on failure - this is what they are for. 或者更好的是:在失败时抛出异常 - 这就是它们的用途。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.