我有以下脚本通过json显示数据库记录。它工作得很好。
我的问题是如何使用它创建一个安全的API,以便在用户放置api时说
http://www.waco.com/profile.php?id=0990999&security=xxxxxxxxx
在他们的网站上,
它将从我的服务器中提取信息并将其显示在他们的网站上。下面是整个工作代码
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
$(document).ready(function(){
var formhtml = "logreq=1";
var postURL= 'profile.php';
$.ajax({
type: "POST",
url: postURL,
data: formhtml,
dataType: JSON,
success: function(html){
var output= '<table class="logtable"><tbody><thead><th>Log</th><th>Username</th><th>Date</th><th>Event</th></thead>';
var logsData = $.parseJSON(html);
for (var i in logsData.logs){
output+="<tr><td>" + logsData.logs[i].title + "</td><td>" + logsData.logs[i].user + "</td><td>" + logsData.logs[i].date+ "</td><td>" + logsData.logs[i].log+"</td></tr>";
}
//write to container div
$("#log_container").html(output);
},
error: function (html) {
alert('Oops...Something went terribly wrong');
}
});
});
</script>
</head>
<body>
<div id="log_container">
</div>
</body>
</html>
<?php
$db = mysqli_connect("localhost","root","","profile_database");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
?>
请我帮忙。
答案 0 :(得分:0)
我假设您的示例过于简单化,并且您将考虑阻止SQL注入以及任何其他验证,以确保您获得预期的数据。
话虽如此,我会将您的PHP代码放在一个单独的文件中,供用户调用并将代码放入其中,如下所示:
if(isset($GET['id']) && isset($GET['security'])){
$id = $GET['id']; $secure = $GET['security']; // TODO: escape these strings
$db = mysqli_connect("localhost","root","","profile_database");
//MSG
$query = "SELECT * FROM logs LIMIT 20 Where id = $id And security = $secure";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
}
希望有所帮助。 This是开始的好地方。我还会研究像CodeIgniter或Cake这样的PHP框架,它们可以帮助您正确构建API。