Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SQLite PDO Check if user is in table?

Tags:

php

sqlite

pdo

I'm trying to create a script that checks if the provided username is in the table "users", but the "if" statement is always returned false. The users table only has the one column "username", listing all the users. What am I doing wrong?

$dbh = new PDO("sqlite:db.sqlite");
$stmt = $dbh->prepare("SELECT username from users where username = :name");
$stmt->bindParam(":name", $user);
$stmt->execute();

if($stmt->rowCount() > 0)
{
    //in the table
}
else{
    //not in the table
}

The whole script:

<?php
require_once 'mclogin.class.php';
$api = new MinecraftAPI();
$user = $_POST['user'];
$password = $_POST['pword'];
if($api->login($user, $password)){
print $user;
$dbh = new PDO("sqlite:db.sqlite");
$stmt = $dbh->prepare("SELECT username from users where username = :name");
$stmt->bindParam(":name", $user);
$stmt->execute();

if($stmt->rowCount() > 0)
{
    echo "You are whitelisted";
}
else{
    echo "You are not whitelisted";
}

}else{
echo "Bad login";
}
?>

the page that send the info:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>

      <form name="input" action="login.do.php" method="post">
Username: <input type="text" name="user">
Password: <input type="password" name="pword">
<input type="submit" value="Submit">
      </form>  
    </body>
</html>
like image 421
Jeremy Avatar asked May 22 '26 07:05

Jeremy


1 Answers

Note:

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

You should use the below instead, just use the fetch() method to check whether the result is empty.

$dbh = new PDO("sqlite:db.sqlite");
$stmt = $dbh->prepare("SELECT 1 from users where username = :name");
$stmt->bindParam(":name", $user);
$stmt->execute();

// use fetch instead of rowCount
if ($stmt->fetch()) {
  // in the table
} else {
  // not in the table
}
like image 105
xdazz Avatar answered May 23 '26 22:05

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!