I have the following script which is not working as I am expecting it to work:
$DBH = new PDO( "mysql:host=localhost;dbname=database_name", "user", "pass" );
$DBH -> setAttribute( PDO::ATTR_ERRMODE, P开发者_运维技巧DO::ERRMODE_EXCEPTION );
$STH = $DBH -> prepare( "select count( users_id ) from table1 where username = :username" );
$STH -> bindParam( ':username', $_POST['username'], PDO::PARAM_STR, 100 );
$STH -> execute();
$strCount = $STH -> rowCount();
if( $strCount == 1 ) {
echo $strCount;
echo "user has already registered, do nothing";
} elseif ( $strCount == 0 ) {
echo $strCount;
echo "user has not registered, insert into db";
} else {
echo $strCount;
echo "something is wrong, should only ever be 0 or 1";
}
It always seems to return 1 for $strCount
In table1, I just have 1 row where the username is username1. If the posted value is username1, then I expect $strCount to be 1, but for some reason, if the posted value is username2, I am still getting $strCount as 1.
Anyone know what I am doing wrong?
you are doing count twice ! count() and rowcount(). PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
Try doing regualr fetch
$count = $db->query("select count(*) from table")->fetch();
You're doing a COUNT() in the query, which means you'll only ever get a single row back, with one field, containing the count of the records.
You have to retrieve that row and field, then base your decisions on that value.
count(blah) will return a single row with the value of the count. Instead of calling rowCount(), I think you need to call fetch(..) after you execute and read the value from there. This is based on the PHP documentation.
http://www.php.net/manual/en/pdostatement.fetch.php
I'm not a PHP developer so I don't want to give you bad code.
精彩评论