【发布时间】:2015-06-25 20:52:24
【问题描述】:
您好,我目前正在尝试将数据添加到我的用户登录数据库,但是由于某种原因,当我注册新用户时,我的数据库没有更新。
这是我来自 user.inc.php 的代码:
<?php
//checks if username already exists in database
function user_exists($user)
{
$user = mysqli_real_escape_string($user);
$total = mysqli_query("SELECT user_id FROM user_system WHERE user_name= ('$user')");
return (mysql_result($total, 0) == '1') ? true : false;
}
//checks if username and password combo is valid
function valid_credent($user, $pass)
{
$user = mysqli_real_escape_string($user);
$pass = sha1($pass);
$total = mysqli_query("SELECT COUNT user_id FROM users
WHERE user_name = '$user' AND
user_password = '$pass' ");
return(mysql_result($total, 0) == '1') ? true : false;
}
//add user to database
function add_user($user, $pass)
{
$user = mysqli_real_escape_string(htmlentities($user));
$pass = sha1($pass);
$queryStr = "INSERT INTO users (user_name, user_password) VALUES ('$user', '$pass')";
$R = mysqli_query($mysqli,$queryStr);
}
?>
当我尝试添加视图错误时,我的注册页面上也有警告
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/PostalCloud/core/user.inc.php on line 8
第 8 行:
return (mysql_result($total, 0) == '1') ? true : false;
我尝试过使用“sanitize()”,但它不存在。
更新:修改代码后仍然出现错误。这是我的 register.php 代码的一部分,我有一个使用 mysqli 连接到数据库的 init.inc.php。
<?php
include('init.inc.php');
$errors = array();
if(isset($_POST['username'], $_POST['password'], $_POST['repeatPassword']))
{
if(empty($_POST['username']))
{
$errors[] = 'The username cannot by empty. ';
}
if(empty($_POST['password']) || empty($_POST['repeatPassword']))
{
$errors[] = 'The password cannot by empty. ';
}
if($_POST['password'] !== $_POST['repeatPassword'])
{
$errors[] = 'Password verification failed. ';
}
if(user_exists($_POST['username']))
{
$errors[] = 'The username you entered is already taken. ';
}
if(empty($errors))
{
add_user($_POST['username'], $_POST['password']);
$_SESSION['username'] = htmlentities($_POST['username']);
header('Location: protected.php');
die();
}
}
?>
init.inc.php:
<?php
session_start();
$exceptions = array('register', 'login');
$page = substr(end(explode('/',$_SERVER['SCRIPT_NAME'])), 0, -4);
if(in_array($page, $exceptions) === false)
{
if(isset($_SESSION['username']) === false)
{
header('Location: login.php');
die();
}
}
$mysqli = mysqli_connect('localhost','root','', 'user_system');
$path = dirname(__FILE__);
include("{$path}/core/user.inc.php");
?>
【问题讨论】:
-
不要使用 mysql_* 函数。这些已弃用,不支持 MySQL 的新功能。
-
确实如此。你似乎在那里来回切换,这很奇怪。此外,切换到 mysqli 准备好的语句将防止必须转义每个变量。我建议使用更安全、更高效的连接重新开始此脚本