尝试使用PHP检查MySQL数据库中是否已经存在用户名 [英] Trying to check if username already exists in MySQL database using PHP
问题描述
我查看了许多与我的问题类似的文章,并尽我所能实施了他们的解决方案(据我所知).但是,每次执行此脚本时,都会执行else块中的代码(即使输入的用户名已经存在).
I've looked at the many other posts that were similar to my issue and implemented their solutions (as far as I can tell) as exactly as I could. However, every time I execute this script, the code in the else block is executed (even when the username inputted is one that is already present).
表名是用户",而我要搜索的列是用户名".
表单中的输入被读入$username
,并且我验证了使用 echo 正确地将其读入. $con
包含与服务器的连接.
The table name is 'Users' and the column that I am trying to search is 'username'.
The input from my form was read into $username
and I verified that it was read in properly using echo. $con
contains the connection to the server.
在某些时候,我还放入了echo $query
(什么都没打印)和echo mysql_num_rows($query)
(什么都没打印).
At some point I also put in echo $query
(nothing was printed) and echo mysql_num_rows($query)
(nothing was printed).
这是代码的相关部分.非常感谢您提供一些提示.
Here's the relevant segment of the code. Would really appreciate some tips.
$query = mysql_query("SELECT username FROM Users WHERE username=$username", $con);
if (mysql_num_rows($query) != 0)
{
echo "Username already exists";
}
else
{
...
}
显然我应该为服务器使用mysqli,而我检查num_rows的方式是通过执行$ query-> num_rows,因为它是对象的属性.感谢您的所有帮助!
Apparently I was supposed to be using mysqli for my server and the way I checked the num_rows for that was by doing $query->num_rows since it was a property of the object. Thanks for all the help!
推荐答案
将查询更改为喜欢.
$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");