PHP MYSQL在重复条目上显示错误消息

时间:2018-12-20 14:15:11

标签: php mysql

我有以下代码来验证条目是否重复,但没有显示错误,而是跳至index.php,我需要它来显示错误消息..有人可以帮我吗?

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");
}

1 个答案:

答案 0 :(得分:1)

只是改变

if ($result >1){}

TO

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

$result是一个数组,因此请使用count()对数组元素进行计数。

编辑。

而不是:$ sql2 =“ SELECT COUNT(*)作为用户名=的用户计数?”;

您可以

$sql2 = "SELECT userID,firstname,lastname FROM users WHERE username = ?";