Work-Around for PHP5's Pdo Rowcount MySQL Issue

Work-around for PHP5's PDO rowCount MySQL issue

You can issue a SELECT FOUND_ROWS() query right after the original SELECT query to get row count.

$pdo->query("SELECT * FROM users");
$foundRows = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();

See also: MySQL Docs on FOUND_ROWS()

PHP PDO fetch error. rowcount = 1 but fetchall returns false;

Looks like the problem is:

$this->selectCustomerAddressStatement->closeCursor();

.. which is being called after the row count. Closing the cursor probably releases the results of the statement which is why fetching returns nothing. Move that call to the end when you're done with fetching the data.

PDO rowCount() alternative

This is a perfect case of "XY problem". But luckily you managed to explain your real problem along with main question. You don't actually need no rowcount() here.

What you really need is a mysql specific INSERT .. ON DUPLICATE KEY UPDATE query

Which will either insert or update the record based on whether it exists or not.

rowCount() returns incorrect number of rows

You are selecting COUNT(*), therefore you're request will always result in 1 answer : the row count itself.

You can either set an alias on COUNT and use it...

$sql = $db->query("SELECT COUNT(*) AS my_count FROM blog_active_users WHERE `username` = {$user}");
$num_rows = $sql->fetch(PDO::FETCH_OBJ)->my_count;

... or select everything :

$sql = $db->query("SELECT * FROM blog_active_users WHERE `username` = {$user}");
$num_rows = $sql->rowCount();

This code always return $id but not $first_name

I think you can use fetch() to fetch the entire row and then call each column by its name

$stmt->execute();
$result = $stmt->fetch();
$id = $result['id'];
$name = $result['name'];
//and so on for all the columns

fetchColumn() vs rowCount() just for check existing

Doesn't matter.

If you're selecting only one row, both methods will be equally fast.

BTW, your query is superfluous.

SELECT 1 FROM table WHERE col = ? LIMIT 1

is more than enough

Well, regarding speed difference. Given your code, in five minutes i will find several spots which are hundred times less efficient/slower than this negligible difference. Just to show you that your concern about single trifle operation is superfluous. Interpreted web languages are not about microsecond optimizations.

Your real concern should be index for the col field. As long as you have it, your code is fast either way. If not - no PDO function will be able to make it fast.

But if you still want a choice, I'd stick to fetchColumn(), as it seems answer the question more directly



Related Topics



Leave a reply



Submit