在继续之前,SELECT * FROM’users’WHER”username’=’. $_POST [ ‘用户名’];只是要求sql注入.我建议你使用PHP数据对象 –
http://php.net/manual/en/book.pdo.php.
据我所知,我将如何通过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响应.请求完成后,将执行回调函数,数据是来自请求的响应.因为我们指定该响应将是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','DATABASE_USERNAME','DATABASE_PASSWORD',array(PDO::MysqL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//prepare our query.
$query = $db->prepare('SELECT * 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->rowCount() > 0));
现在回顾一下,我们的jQuery脚本将发布到validation.PHP,它从数据库中选择一个用户名.它将返回一个JSON对象,该对象具有exists的键,该键是一个布尔值,指示用户名是否已作为数据库中的行存在.通过jQuery完成请求后,您可以根据查询结果执行所需操作.我希望这是一个彻底的解释,并引导您达到您希望实现的目标.