<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>注册</title>
</head>
<?php
if(isset($_POST["Submit"]) && $_POST["Submit"] == "注册")
{
$user = $_POST["username"];
$psw = $_POST["password"];
$psw_confirm = $_POST["confirm"];
if($user == "" || $psw == "" || $psw_confirm == "")
{
echo "<script>alert('请确认信息完整性!'); history.go(-1);</script>";
}
else
{
if($psw == $psw_confirm)
{
mysql_connect("localhost","root",""); //连接数据库
mysql_select_db("用户表"); //选择数据库
mysql_query("set names 'gdk'"); //设定字符集
$sql = "select username from user where username = '$_POST[username]'"; //SQL语句
$result = mysql_query($sql); //执行SQL语句
$num = mysql_num_rows($result);
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登陆</title>
</head>
<?php
if(isset($_POST["submit"]) && $_POST["submit"] == "登陆")
{
$user = $_POST["username"];
$psw = $_POST["password"];
if($user == "" || $psw == "")
{
echo "<script>alert('请输入用户名或密码!'); history.go(-1);</script>";
}
else
{
mysql_connect("localhost","root","");
mysql_select_db("用户表");
mysql_query("set names 'gbk'");
$sql = "select username,password from user where username = '$_POST[username]' and password = '$_POST[password]'";
$result = mysql_query($sql);
$num = mysql_num_rows($result);
mysql_num_rows
函数是用来获取查询结果集中的行数的。对于你的代码,如果执行 SQL 查询语句失败,那么 $result
变量会为 false,此时调用 mysql_num_rows
函数会报错。
可以通过以下方式来修改代码,避免因查询失败而导致的错误:
注册页面:
...
$result = mysql_query($sql);
if ($result) {
$num = mysql_num_rows($result);
} else {
echo "<script>alert('查询失败!'); history.go(-1);</script>";
exit;
}
...
登录页面:
...
$result = mysql_query($sql);
if ($result) {
$num = mysql_num_rows($result);
} else {
echo "<script>alert('查询失败!'); history.go(-1);</script>";
exit;
}
...
此外,建议不要再使用 mysql
扩展库来连接 MySQL 数据库,因为该库已经被废弃,不再受到官方维护,且存在一些安全性问题。推荐使用 mysqli
或 PDO
扩展库来连接 MySQL,例如:
// mysqli 扩展库连接 MySQL
$conn = mysqli_connect("localhost", "root", "", "用户表");
if (!$conn) {
die("连接失败:" . mysqli_connect_error());
}
// PDO 扩展库连接 MySQL
$conn = new PDO("mysql:host=localhost;dbname=用户表", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
建议在使用 MySQL 时保证查询语句的安全性,使用参数化查询或其他防止 SQL 注入的方式,避免程序被攻击。