Check if PDO executed query has results to fetch

时间:2015-09-30 23:19:30

标签: php mysql pdo

I have an object to run all my database queries and in that object I have a method called runQuery() that is called for any type of query.

This is just an illustration code:

public function runQuery($query){
    $stmt->prepare($query);
    $stmt->execute();

    return $stmt->fetchAll();
}

My problem is that when I run $stmt->errorCode(); to see if everything went fine I receive the error code: HY000

After some search I discovered that this error is triggered everytime I do a fetchAll() on queries that have nothing to fetch like INSERT INTO, UPDATE or DELETE.

My question is, how can I verify if the executed query has content to fetch or not without exploding the query to see if the first word is not one of those three?

1 个答案:

答案 0 :(得分:3)

您只是从此功能返回错误值

学习者经常会发现过度复杂化他们的代码,只是因为他们知道没有正确的方法,这非常简单和强大。然后他们让它变得更复杂,问一个问题如何解决由最初错误过于复杂的方法引起的问题。但所有这些都可以通过一种非常简单的方式解决:

您必须返回语句,而不是行。它将使我们的功能非常方便,更有用,但它将保持简单,如插图代码"。它会解决你的问题只是副作用。

public function runQuery($query, $data = array()){
    $stmt->prepare($query);
    $stmt->execute($data);
    return $stmt;
}

全部您需要的代码

想一次获得所有行吗?只需按照这种方式调用您的函数

$obj->runQuery($sql)->fetchAll();

正如您所看到的,在这种情况下,获取方法可以简单地“链接”#34; runQuery()方法调用,这要归功于非常简洁的OOP语法功能,称为"方法链接"。您只需要返回语句,而不是结果。

写作不多,但灵活性极大。现在,您可以获得所需的任何结果类型。

事实上,您只是将自己局限于一种结果集类型,这使得获取另一种类型变得复杂。但是PDO已经有数十亿个结果集类型 - 你只需要使用它们。

说,你只需要一个用户名。你会做什么功能?有嵌套数组的麻烦?怎么样呢

$name = $obj->runQuery("SELECT name FROM users WHERE id=?",[$id])->fetchColumn();

看,PDO已经有了一个方便的方法。单排怎么样?

$user = $obj->runQuery("SELECT * FROM users WHERE email=?",[$email])->fetch();

或者,如果你想获得一个列,但不是一个嵌套但简单的一维数组? PDO再次为您提供了一种方法:

$ids = $obj->runQuery("SELECT id FROM news WHERE date=?",[$date])->fetchAll(PDO::FETCH_COLUMN);

还有其他很棒的模式,我在文章中描述了The only proper guide on PDO。要把它们全部抛弃?真的?

或者,请考虑DML查询的初始问题。如果您想获得受影响的行数,该怎么办? voila -

$inserted = $obj->runQuery($insertQuery,$insertData)->rowCount();

看 - 你需要的只是返回语句然后使用方法链来获得所需形式的结果。

作为奖励,您甚至不需要重写使用内部fetchAll()调用的现有代码。如果使用foreach循环返回结果 - 您仍然可以使用相同的代码,使用返回的语句完全相同:

$data = $obj->runQuery($sql);
foreach($data as $row) ...

- 试试吧,它有效!