有几点需要考虑:
1.) 您没有使用参数化 SQL 查询,因此您的数据库对 SQL 注入开放。我更改了您的查询结构以演示如何使用参数化查询。请停止这样做。这是有关此主题的链接。阅读它、添加书签并参考它,直到您理解为止。这很重要,而且只要你做了几次,就不难了。
https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection
2.) 当你使用ajax时,就会发生这样的情况。您的主 html 页面正在向另一个页面发送 ajax 查询。该页面接收响应,执行任何代码,然后将答案发送回发送请求的主 html 页面的 ajax 函数。
该响应是在 ajax 函数的成功块中收到的。我认为来回传递数据的最简单方法是使用 JSON 格式。
3.) php 中回显的任何内容都将发送到 ajax 函数。
4.)我的示例中的数据是 json 字符串而不是 json 对象,因此您必须将字符串转换为 json 对象。
5.)构建新代码时,请分小块进行,直到您正在处理的任何内容按照您期望的方式工作为止。然后修饰工作代码以完成您想要的操作。这将为您节省故障排除的时间,并帮助您在花费数小时对您认为将要发生的事情进行编码之前找出代码的最佳工作流程。
6.) 您可以使用姓名和电子邮件来验证登录,但姓名很常见,人们可以共享电子邮件。我会做一些类似电子邮件/用户名和密码的事情。对于密码,请使用 php 的本机密码函数。
http://php.net/manual/en/faq.passwords.php http://php.net/manual/en/faq.passwords.php
因此,这里有一个示例,应该可以帮助您走上正确的道路。
在你的login.php上将你的ajax函数更改为:
$.ajax({
type: "POST",
url: "success.php",
data: formData,
processData: false,
contentType: false,
cache: false,
dataType: 'application/json; charset=utf-8',
success: function(response){
console.log('Ajax tried.');
console.log(response);
var data = JSON.parse(response); //Change from string to object.
console.log(data);
if (data['success']) {
console.log('It worked!!!!');
//The user's name and email returned a
//result from the user's table.
} else{
console.log('You have an error.');
console.log(data['errors']);
//Here are your errors. Do something with them.
}
}
});
将您的 success.php 更改为:
<?php
session_start(); //Always do first.
$mysqli = mysqli_connect("localhost","root","","ajax1");
if (isset($_SESSION['id'])){ //<--This should not be here. This should
//be tested for on the login.php page.
$errors['logged_in'] = TRUE;
}
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE name=? and email=?"; //<--Use placeholders.
//Remember this: Prepare, bind, Execute.
$stmt = $mysqli->prepare($query); //Prepare
$stmt->bind_param("ss", $_POST['name'], $_POST['email']); //Bind
$stmt->execute(); //Execute.
$result = $stmt->get_result()->fetch_assoc();
if($result){
$_SESSION['name'] = $result['name']; //Safer to use data from db instead of post.
$_SESSION['id'] = $result['userid'];
}else{
$errors['user_exists'] = FALSE;
}
$stmt->close(); //Important to free up resources for your next query.
$response = array();
if(isset($errors) && $errors){
$response['success'] = FALSE;
$response['errors'] = $errors;
} else{
$response['success'] = TRUE;
}
echo json_encode($response); //<-- This is what gets sent back to ajax function.
?>
希望这可以帮助:)