-1

I have the following code to validate if an entry is duplicated or not, but instead of showing the error it just skips to index.php and I need it to show the error message.. can someone help me out please?

if ($valid) {
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //$password = md5($password);

    $sql2 = "SELECT COUNT(*) as count FROM users WHERE username = ?";
    $q2 = $pdo->prepare($sql2);
    $q2->execute(array($username));
    $result = $q2->fetchAll();
    if ($result >1){
        echo '<script language="javascript">';
        echo 'alert("user already exists")';
        echo '</script>';
    }else{
        $sql = "INSERT INTO users (username,password,role) values(?, ?, ?)";
        $q = $pdo->prepare($sql);
        $q->execute(array($username,$password,$role));
    }
    Database::disconnect();
    header("Location: index.php");
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149

1 Answers1

1

Just change

if ($result >1){}

TO

if (count($result) > 0){}

$result is an array so use count() to count array elements.

Edit.

Instead of : $sql2 = "SELECT COUNT(*) as count FROM users WHERE username = ?";

You could

$sql2 = "SELECT userID,firstname,lastname FROM users WHERE username = ?";
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34