Reputation: 310
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?
Upvotes: 4
Views: 3829
Reputation: 160973
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.
//....
}
Upvotes: 0
Reputation: 212522
$stmt->rowCount() after the execute(), but doesn't work with all databases... try it with MySQL and see what you get.
Upvotes: 4