duan7007
duan7007
2019-05-13 10:38

MYSQL检查数据库中是否已存在用户名[重复]

已采纳

This question already has an answer here:

My code was working but after I inserted a query to check if the first name in MYSQL database already exists, it does not work anymore. Here you can see my code, if you have any tip on how to make this work, I will appreciate it. Thank you very much!

I have tried to work with mysql_num_rows command, but it seems like I didn't use it correctly.

<?php 

require_once __DIR__.'/connect.php';

$sName = $_POST['txtName'];

$query = mysql_query("SELECT * FROM users WHERE firstName = '$sName' ");
if (mysql_num_rows ($query) > 0){
    echo 'User with this name already exists';
}else{
    try {
        $stmt = $db->prepare('INSERT INTO users
    VALUES (null, :sName, :sLastName, :sEmail, :sCountry )');
        $stmt->bindValue(':sName', $sName);

        $stmt->execute();
        echo 'New user was successfully inserted';
    } catch (PDOEXception $ex) {
        echo $ex;
    }
}
</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dqc42632 dqc42632 2年前

    You are trying to use mysql_query when you have (based on the rest of your code that is working) a PDO connection. Change your query to use your existing connection:

    try {
        $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE firstName = :sName");
        $stmt->bindValue(':sName', $sName);
        $stmt->execute();
        $num_rows = $stmt->fetchColumn();
    }
    catch (PDOEXception $ex) {
        echo $ex;
    }
    if ($num_rows > 0) {
        echo 'User with this name already exists';
    }
    else {
        // the rest of your code here
    
    点赞 评论 复制链接分享