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 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。
  • ¥15 GitHubssh虚拟机连接不上
  • ¥15 装完kali之后下载Google输入法 重启电脑后出现以下状况 且退不出去 桌面消失 反复重启没用
  • ¥15 ESP-IDP-BLE配网连接wifi
  • ¥15 ue2.6.12版本用的若以,安装gojs,引入import * as go from 'gojs';报错
  • ¥15 服务器上的网站安装php5.6版本