From manual:
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
So PDOStatement::rowCount()
isn't working for me with SELECT
queries. I have query to which I must be able to add AND
conditions to WHERE
clause like this:
$sql = "SELECT * FROM customers WHERE 1=1";
if ($name)
$sql .= " AND `name` LIKE :name";
if ($type)
$sql .= " AND `type` = :type";
if ($category)
$sql .= " AND `category` = :category";
if ($group)
$sql .= " AND `group` = :group";
if ($area)
$sql .= " AND `area` = :area";
$query = $pdo->prepare($sql);
if ($name)
$query->bindValue(':name', '%' . $name . '%');
if ($type)
$query->bindValue(':type', $type);
if ($category)
$query->bindValue(':category', $category);
if ($group)
$query->bindValue(':group', $group);
if ($area)
$query->bindValue(':area', $area);
$query->execute();
Do I need to do it like following code or is there some easier way to do it?
$sql = "SELECT * FROM customers WHERE 1=1";
$count = "SELECT COUNT(*) FROM customers WHERE 1=1";
if ($name) {
$sql .= " AND `name` LIKE :name";
$count .= " AND `name` LIKE :name";
}
if ($type) {
$sql .= " AND `type` = :type";
$count .= " AND `type` = :type";
}
if ($category) {
$sql .= " AND `category` = :category";
$count .= " AND `category` = :category";
}
if ($group) {
$sql .= " AND `group` = :group";
$count .= " AND `group` = :group";
}
if ($area) {
$sql .= " AND `area` = :area";
$count .= " AND `area` = :area";
}
$query = $pdo->prepare($sql);
if ($name)
$query->bindValue(':name', '%' . $name . '%');
if ($type)
$query->bindValue(':type', $type);
if ($category)
$query->bindValue(':category', $category);
if ($group)
$query->bindValue(':group', $group);
if ($area)
$query->bindValue(':area', $area);
$query->execute();