PHP使用PDO连接Mysql的返回值问题

我用PHP写了一个用户登录系统,数据库主键是用户名user_name。点击界面上的“注册”按钮,就向mysql库里插入一条数据。
$dbh=new PDO("mysql:host=192.168.5.100:3306;dbname=stu_info",'flash','****');
$dbh->exsec("insert into users values('$user_name','$pwd');");
我现在想实现的功能是:如果输入的用户名与数据库的某一条数据重复,则返回一个警告:“用户名已存在”。应该如何写?

// pdo对象的query方法返回一个PDOStatement对象 调用PDOStatement对象的rowCount()方法可以获取查询的返回行数
if($dbh->query("select * from `users` where `user_name`='$user_name'")->rowCount())
    echo '用户名已存在!';

追问

你是先判断再插入,能不能通过PDO的返回值来判断用户名是否重复啊?

追答

if($dbh->exec("insert into users values('$user_name','$pwd') where not exists(select * from `users` where `user_name`='$user_name');
")->rowCount())
echo '用户名已存在!';

温馨提示:答案为网友推荐,仅供参考