在继续之前,SELECT * FROM 'users' WHERE 'username' = '. $_POST['username']; 只是在请求 SQL 注入。我建议你使用PHP Data objects。
所以据我了解,我也必须通过 $.ajax 传递 POST 值,对吗?如果是,我将如何通过validation.php 文件访问它们?
因为这是一个简单的请求,我建议你使用JQuery的方法$.post()。这是一个基于您正在尝试做的示例。
$.post('validation.php',{username: $('#username').val()}, function(data){
if(data.exists){
//tell user that the username already exists
}else{
//username doesn't exist, do what you need to do
}
}, 'JSON');
jQuery 的 post 方法有 4 个参数 $.post(url, data, callback, datatype)。在上面的示例中,我们会将带有$('#username').val() 的用户名发布到validation.php,并期待JSON 响应。当请求完成时,将执行回调函数,data 是请求的响应。因为我们指定该响应将是JSON,所以我们可以像访问 javascript 中的原生对象一样访问它。现在让我们转到validation.php
如上所述,我建议您使用 PDO 作为数据库驱动程序。所以在这个例子中,我将向你展示它的基本用法。
//set the headers to be a json string
header('content-type: text/json');
//no need to continue if there is no value in the POST username
if (!isset($_POST['username'])) {
exit;
}
//initialize our PDO class. You will need to replace your database credentials respectively
$db = new PDO('mysql:host=DATABASE_HOST;dbname=DATABASE_NAME;charset=utf8mb4', 'DATABASE_USERNAME', 'DATABASE_PASSWORD');
//prepare our query.
$query = $db->prepare('SELECT COUNT(*) FROM users WHERE username = :name');
//let PDO bind the username into the query, and prevent any SQL injection attempts.
$query->bindParam(':name', $_POST['username']);
//execute the query
$query->execute();
//return the JSON object containing the result of if the username exists or not. The $.post in our jquery will access it.
echo json_encode(array('exists' => $query->fetchColumn() > 0));
现在回顾一下,我们的 jQuery 脚本将发布到validation.php,它会从数据库中选择一个用户名。它将返回一个JSON 对象,该对象的键为exists,它是一个布尔值,指示用户名是否已作为数据库中的一行存在。当通过jQuery完成请求后,您可以根据查询结果做您需要的事情。