doufubian3479 2017-08-14 20:35
浏览 39
已采纳

Php / PDO用户存在吗?

I know there are already some posts about it, but I got other solution than others:

    $sql= 'SELECT * FROM pr_users WHERE nick = :nick ';
        $sqldot = $db->prepare($sql);
        $checkif = $sqldot->execute(array(':nick' => $nick));

        if (count($checkif) == 1) {
            $_SESSION['ng'] = "<p class=\"text-warning\">Nickname already exists!</p>";
            header("location: ../register.php");
        } else {
            $final++;
            $_SESSION['nick'] = $nick;
        }

$db is defined here:

$db = new PDO(
    "mysql:host=" .dbserver. ";dbname=" .dbname,dbuser,dbpass,
    array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET CHARACTER SET utf8"
    )
  );

I count if $checkif has any characters in, but for some reason even if "name" does not exist -> $checkif still has some characters in, so it tells me that it already exist, which is wrong.

  • 写回答

1条回答 默认 最新

  • doushuangai9733 2017-08-14 20:42
    关注

    execute function Returns TRUE on success or FALSE on failure. Your if condition if (count($checkif) == 1) will be always true.

    You need to fetch the results after execute() and check it count for results.

    $checkif = $sqldot->execute(array(':nick' => $nick));
    $result = $sqldot->fetch();
       if (!empty($result)) {
            $_SESSION['ng'] = "<p class=\"text-warning\">Nickname already exists!</p>";
            header("location: ../register.php");
        } else {
            $final++;
            $_SESSION['nick'] = $nick;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?