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

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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘