如何解决php和mysql_num_rows无法检测数据库中是否存在某些内容
|| 我在网站上有一个表单,需要在将表单数据输入数据库之前进行验证。 它通过用户mysql_num_rows函数检查用户名是否已经存在。但是我似乎无法正常工作。测试时,不允许添加新的用户名。 这是使用的完整代码:<?php
session_start();
include(\"databaseConnect.php\");
// Insert a row of information into the table \"example\"
// check if username is already in database
if(mysql_num_rows(mysql_query(\"SELECT userName FROM registeredUsers WHERE userName = \'$_POST[userName]\'\"))){
echo \"Username: \". $_POST[userName].\" already exists in the Database<br><br>\";
echo \"You will be redirect back to the form in 5 seconds\";
$ref = $_SERVER[\'HTTP_REFERER\'];
header( \'refresh: 5; url=\'.$ref);
//check if hemis is already in database
}elseif(mysql_num_rows(mysql_query(\"SELECT hemis FROM registeredUsers WHERE hemis = \'$_POST[hemis]\'\"))){
echo \"Student [Hemis] Number: \". $_POST[hemis].\" already exists in the Database<br><br>\";
echo \"You will be redirect back to the form in 5 seconds\";
$ref = $_SERVER[\'HTTP_REFERER\'];
header( \'refresh: 5; url=\'.$ref);
// if all the conditions above are fine,it will insert the data to MySQL
}else{
mysql_query(\"INSERT INTO registeredUsers
(firstName,lastName,hemis,userName,MAC) VALUES(\'$_POST[firstName]\',\'$_POST[lastName]\',\'$_POST[hemis]\',\'$_POST[userName]\',\'$_POST[mac]\' ) \")
or die(mysql_error());
echo \"Data Inserted! <br><br>\";
}
非常感谢 :)
解决方法
我会完全重写一下。它受到SQL注入的影响,效率低下并且过于简洁。另外,使用PHP mysqli扩展程序通常会更好
另外,请确保将$ _POST变量名称括在引号中。您已将它们写为常量,而不是字符串。 (除非您已在代码的其他地方定义了代表字符串值的常量,否则这是一个错误。在开发时请打开PHP警告。)
$safe_username = mysqli_real_escape_string($_POST[\'userName\']);
$sql = \"SELECT userName FROM registeredUsers WHERE userName=\'$safe_username\' LIMIT 1\";
$result = mysqli_query($database_connection,$sql);
if (mysqli_num_rows($result))
{
// username already found code
mysqli_free_result($result);
}
else
{
$safe_hemis = mysqli_real_escape_string($_POST[\'hemis\']);
$sql = \"SELECT hemis FROM registeredUsers WHERE hemis=\'$safe_hemis\' LIMIT 1\";
// Side note,LIMIT 1 tells the database engine to stop looking after it\'s found one hit. More efficient as you\'re only looking for a Boolean value anyway.
$result = mysqli_query($database_connection,$sql);
if (mysqli_num_rows($result))
{
// hemis found code
mysqli_free_result($result);
}
}
其余的您可能可以从中弄清楚。
请验证并转义所有输入。验证包括检查完整性-数据是否在范围内(字符串长度,数字范围等),等等。所有输入都是有害的!
您确实也不想依赖HTTP_REFERER。用户代理并不总是通过引荐来源网址。
另外,我知道这没什么大不了,但是使用CSS而不是<br>
。如果您使用的是XHTML文档类型,则必须正确关闭所有标签,因此<br>
将变为<br />
。无论如何,这是一个好主意。
, 最好也检查mysql_query的结果。它可能返回一个可以获取行数的结果集,但是当查询失败时它可能返回false。在这种情况下,您将没有结果集,而mysql_count_rows将失败。失败,您将其解释为0行。
除了Matty给您的所有出色建议之外,我还将做一些额外的检查和严格的类型检查。
if ($result = mysql_query(\'....\') === false)
{
die(\'Your query failed in the first place. Error: \' . mysql_error());
}
您可以进行许多改进(例如在查询中使用count等),但是我认为您至少应该进行这些检查。它可以帮助您了解实际出了什么问题,而不必猜测。无论您是初学者还是经验丰富的程序员,都可以节省大量调试时间。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。