duan7007 2019-05-13 10:38
浏览 336
已采纳

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 2019-05-13 10:46
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥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 我看了您的文章,遇到了个问题。