4

There are a lot of questions on this and I have done a lot of research. However, I am still wondering if I am doing this right.

Here is my statement (I've simplified it):

    try {
        $stmt = $pdc_db->prepare("SELECT * FROM table WHERE color = :color"); 
        $stmt->bindValue(':color', $selected_color);
        $stmt->execute(); 
        $color_query = $stmt->fetchAll();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); } 

Now, I am using the following to see if this has returned any results:

if (count($color_query) > 0) {

This works, HOWEVER... the SELECT statement will only return one result. So now to access stuff in the results, I am using $color_query[0][colorname]. I know this is because I am using fetchAll(), but I really want to be using fetch()

But if I just use fetch(), I am losing the ability to do a count(), which is pretty simple to me. I know I can do a separate query and check the results of SELECT COUNT(*), but that seems like more work (setting two separate queries up for each)

There must be a way, using PDO in PHP with mySQL, to check if fetch() has returned a result?

1
  • there is no reason to use fetch instead of fetchall Commented Jan 22, 2012 at 5:49

2 Answers 2

4

$stmt->rowCount() after the execute(), but doesn't work with all databases... try it with MySQL and see what you get.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow, this actually worked. In all my searching most places said rowCount() wouldn't work with mySQL, so I never bother trying.
Whether rowCount() works or not depends on whether the underlying database driver uses a real cursor or just returns all results buffered. MySQL for the most part does the latter.
Thanks for the info. I guess the real lesson here is don't assume rowCount() won't work. It DOES work in my situation for PHP PDO with mysql. Hopefully this can save someone else some time.
0

You can do it with fecth, fecth will return false if no results returns.

if ($row = $stmt->fetch()) {
     //get the first row of the result.
     //....
}

3 Comments

sometimes you have to know if there are results before starting the loop.
@Col.Shrapnel He just need the first row of the result, will not need the loop.
well, i re-read the question and it may be so. it is quite unclear however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.