I was using this method to get row-counts for SELECT statements, but it didn’t work correctly for LIMIT statements, so I added code to remove the LIMIT from the sql string, but now it doesn’t work at all!
When I started using queries with a LIMIT X, X at the end, I had to add the section at the top to strip that part from the query, because this method only returns one column – count – but the LIMIT offset would cause it to return nothing.
function dbRowsCount($sql, $data) {
# removes "LIMIT X,X" from query
$no_limit_sql = $sql;
$pos = stripos($sql, " LIMIT");
if ($pos!==false) {
$no_limit_sql = substr($sql, 0, $pos).";";
# logErrors("original sql=".$sql);
# logErrors("pos=".$pos."<br>new sql=".$no_limit_sql);
}
# query SELECT COUNT(*) instead of SELECT...
# returns row-count
$regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/is';
if (preg_match($regex, $no_limit_sql, $output) > 0) {
dbQuery("SELECT COUNT(*) AS count FROM {$output[1]}", $data);
$result = dbFetch();
$last_rowcount = (int)$result["count"];
if ($pos!==false) {
# logErrors("after regex="."SELECT COUNT(*) AS count FROM {$output[1]}");
# logErrors("row count=".$last_rowcount);
}
return $last_rowcount;
} else {
# logErrors("Oops! There was an error:<br>Regex did not match SQL.");
return -1;
}
}
This put directly into MySQL gives count=8:
SELECT COUNT(*) AS count FROM tbl_product WHERE 1 ORDER BY last_update DESC;
The output from the dbRowsCount($sql, $data) method shows this query should end up the same:
original sql=SELECT * FROM tbl_product WHERE 1 ORDER BY last_update DESC LIMIT ?, ?;
pos=59
new sql=SELECT * FROM tbl_product WHERE 1 ORDER BY last_update DESC;
after regex=SELECT COUNT(*) AS count FROM tbl_product WHERE 1 ORDER BY last_update DESC;
row count=0
It was working before, it was returning rows=8 without the part I added for removing “LIMIT X,X” from the query, but only when the LIMIT was 0,X. When I tried LIMIT 5,5 it wouldn’t fetch the column because of the offset, and now it’s returning 0 rows for any values.
I also tried this directly with PDO, it worked correctly for both int and string parameters! But using the PDOStatement->rowCount(). (It’s not recommended for SELECT queries, so I used the above dbRowsCount method).
function dbDebugTest() {
global $db;
# logErrors("Beginning dbDebugTest()");
$stmt = $db->prepare("SELECT * FROM tbl_product WHERE 1 ORDER BY last_update DESC LIMIT ?,?");
$offset = "5";
$display = "5";
$stmt->execute(array($offset,$display));
# logErrors("dbDebugTest() returned rows: ".$stmt->rowCount());
}
What is causing the first method to return 0 rows?
All I can see is that when a
LIMITis present you add a semi colon behind the query. Perhaps that’s the cause of your problem.If that’s not the problem, assuming
dbQueryanddbFetchare working correctly and didn’t change, your table is empty? 🙂OP Answer I was still forwarding the
$dataarray to the query when there are no params anymore (since I removed LIMIT X, X)