Answers for "pdo how to check if got any row"

Go
0

pdo how to check if got any row

// Params
$dbServerName = "localhost";
$dbUserName = "root";
$dbPwd = "";
$dbName = "login";
// Trying to connect to the database
try {
    $con = new PDO("mysql:host=$dbServerName;dbname=$dbName; charset=utf8", $dbUserName, $dbPwd);
}
// If it cant connect connect if will catch and echo an error message
catch(PDOException $e) {
    echo "connection failed: " . $e->getMessage();
}

$user_uid = "userName";
$user_pwd = "userName";

// Making a prepare statement with the $con variable
$statement = $con->prepare("SELECT * FROM users WHERE userName = (:name)");
// Binding a value to (:name) that is in the SQL code above
$statement->bindParam(':name', $user_uid);
// Executing the SQL
$statement->execute();
// Here i check if the row count (Number of rows i got out of the SQL) is above 1
if($statement->rowCount() > 0){
    // If it is then do a while loop with fetch to get results
    while ($row = $statement->fetch()){
       // results
    }
}
else{
    // If the row count is lower or equel to 0 then it will run this code   
}
Posted by: Guest on December-09-2020

Browse Popular Code Answers by Language