【发布时间】:2017-10-07 06:07:47
【问题描述】:
我正在制作一个允许用户为项目获得资金的 Web 应用程序,我已经完成了大部分工作,但我被困在 php 脚本返回正状态代码但没有数据插入 Mysql 数据库的地方。以下是我正在使用的 php 脚本:
代码:
<?php
session_start();
if(!isset($_SESSION['username']))
{
echo "Unauthorised Page Usage Please Relogin to Access All the Page features;";
header('location:login.html');
}
$sponsor=mysql_real_escape_string($_POST['sponsorid']);
$projectid=mysql_real_escape_string($_POST['projectid']);
$pledge=mysql_real_escape_string($_POST['pledgevalue']);
$servername = "localhost";
$usernam = "root";
$password = "";
$dbname = "project";
$httpStatusCode = 400;
$httpStatusMsg = 'Incorrect Username or Password';
$protocol=isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
$connection=new mysqli($servername,$usernam,$password,$dbname);
if (!$connection) {
die("Connection failed: " . $connection->connect_error);
}
$sql1="INSERT INTO `sponsor`(`spon_id`,`project_id`,`spon_amt`,`spon_date_time`) VALUES ('$sponsor','$projectid','$pledge',NOW())";
$result=$connection->query($sql1);
if ($result) {
$Success=200;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$result);
}
else {
$Success=400;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$httpStatusMsg);
}
?>
以下是用于将数据发布到页面的 ajax:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if(this.status===404){
alert(this.responseText);
}
if(this.status===200)
{
alert("Project backed successfully");
window.location.reload(true);
}
}
};
xhttp.open("POST", "sponsor.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param= "sponsorid"+"="+ <?php echo json_encode($_SESSION['username']); ?>+"&"+"pledgevalue"+"="+document.getElementById("pledge").value+"&"+"projectid"+"="+<?php echo json_encode($projectid);?>;
console.log(param);
xhttp.send(param);
}
我已经交叉引用了我的赞助商表,以确保每个字段都相同。代码在我朋友的计算机上运行良好。请帮帮我
更新:$sql1 查询给了我错误代码:1644 当我在数据库中运行它时出现问题(使用 XAMMP)。
请帮忙。
【问题讨论】:
-
混合 API,未定义的变量。你应该启用错误报告,它可能会告诉你很多。还学习如何利用准备好的语句来处理变量的查询
-
警告:使用
mysqli时,您应该使用parameterized queries 和bind_param将用户数据添加到您的查询中。 请勿使用手动转义和字符串插值或连接来完成此操作,因为您将创建严重的SQL injection bugs。意外未转义的数据是一个严重的风险。使用绑定参数不那么冗长,并且更容易检查以检查您是否正确执行。 -
最好将查询字符串直接提供给
prepare调用。正如您在此处演示的那样,中间变量很容易混淆。 -
您还需要考虑使用 JQuery 之类的东西,而不是滚动您自己的 XMLHttpRequest 包装器。
$.ajax以简单易懂的语法完成您在此处看到的所有内容。