Question

I hope this question does not seem vague but I am converting the old mysql statements to the PDO prepared statements and I have searched but cannot find the answer to this. What is the equivalent of $count=mysql_num_rows($stmt); in PDO? I have included my code so you can see what I am doing but basically I am creating a login page for users I have a PDO statement using SELECT to search the database for a matching username and password row. If it comes up with one then it will increase the $count variable to one so that my IF statment is true.

CHECK_LOGIN.PHP

<?php
require 'functions.php';
require 'DB.php';
ob_start();

// Define $myusername and $mypassword 
$myusername=$_POST['myusername']; 
$mypassword =$_POST['mypassword'];
$mypassword = md5($_POST['mypassword']);

checkLogin($conn,$myusername,$mypassword,$stmt);

// Mysql_num_row is counting table row
$count=mysql_num_rows($stmt);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
    session_start();
    $_SESSION['myusername'] = $myusername;
    session_is_registered("myusername");
    session_is_registered("mypassword"); 
    $myusername1 = $_SESSION['myusername'];
    //UPDATE LAST LOGIN IN DATABASE
    date_default_timezone_set('America/Chicago');
    $last_login = date('m/d/Y h:i:s a', time());
    lastLogin($conn,$myusername1,$last_login);
    header("location:form.php");


}
else {

echo "Wrong Username or Password";

}
ob_end_flush();
?>

function in FUNCTION.PHP

function checkLogin($conn,$myusername,$mypassword,$stmt){

$myusername = stripslashes($myusername);
$myusername = mysql_real_escape_string($myusername);
$stmt = $conn->prepare('SELECT * FROM `CLL_users` WHERE `user_name`=:myusername AND `password`=:mypassword');
$stmt->execute(array(':myusername' => $myusername, ':mypassword' => $mypassword));
}
Was it helpful?

Solution

Check example #2 from here: PDOStatement::rowCount

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top