我正在尝试插入从 POST 方法收到的数据。当我插入它时,每个重新编码都会插入 3 次 这是我的代码
$answer = $_POST['answer'];
$code = $_POST['code'];
$sid=$_POST['sid'];
//$user=$_POST['user'];
$user = "root";
$pass = "";
$host= "localhost";
$dbname="offlinesurvey";
date_default_timezone_set('UTC');
$date = date('YmdHis');
$name=$sid.'_'.$date;
$con = mysqli_connect($host,$user,$pass,$dbname);
$sql_create="CREATE TABLE `offlinesurvey`.`lime_survey_$sid` ( `id` INT NULL AUTO_INCREMENT ,whenadded DATETIME, `code` VARCHAR(255) NOT NULL,`answer` VARCHAR(255) NOT NULL , UNIQUE `id` (`id`)) ENGINE = MyISAM;";
if(mysqli_query($con,$sql_create)){
}
else {
"No..No";
}
foreach((array) $_POST as $k => $v) {
echo $v;
$sql = "insert into lime_survey_$sid(user,whenadded,code,answer) values('".$_POST['user'][$k]."',Now(),'".$_POST['code'][$k]."', '".$v."')";
mysqli_query($con,$sql);
}
?>
如何解决这个问题?
最佳答案
在这种情况下,您不需要 foreach
循环。您将始终有相同数量的用户 (1) 在此脚本中插入数据。当数组中存储有多个和/或未知的数据集时,您可以使用foreach
。 $_POST
是一个数组,但您可以像前三行一样访问表单输入:
<?php
$answer = $_POST['answer']; // Set Post array from form to variables
$code = $_POST['code']; // Use could filter/validate here
$sid = $_POST['sid']; // I usually begin these variables with "dirty", "external", etc. so I remember not to trust it.
$user = $_POST['user'];
请注意,您绝不能信任用户输入。您必须将其视为潜在恶意。稍后将详细介绍。
现在您的表单上传存储在 PHP 变量中,您无需再次引用 Post。
适合使用 MySQLI。但是,您使用的代码仍然容易受到注入(inject)和恶意(甚至无辜)代码的攻击(仅当查询是硬编码且不会执行多次时才使用查询)。您需要使用准备好的语句和 mysqli_stmt_bind_param反而。另外,我不会授予数据库用户 CREATE TABLE 权限。相反,最好只用“sid”创建一个列。一旦机器人找到您的网站,这也将使您免受 1082384917 个表的困扰。这将进入一个表“lime_survey”,您应该在数据库中使用适当的字段创建该表。
// Don't forget connection settings. DON'T use root in production.
date_default_timezone_set('UTC');
$whenadded = date("Y-m-d H:i:s");
$con = mysqli_connect($host,$user,$pass,$dbname);
$insert = mysqli_prepare($con, "INSERT INTO `lime_survey` (`sid`, `user`, `whenadded`, `code`, `answer`) values (?,?,?,?,?)");
mysqli_stmt_bind_param($insert, 'sssss', $sid, $user, $whenadded, $code, $answer);
mysqli_stmt_execute($insert);
mysqli_stmt_close($insert);
mysqli_close($con);
此方法将为此脚本的每个实例仅创建一行。此外,它更安全;但是,如果从表中检索数据,请确保正确转义数据(这取决于将使用数据的应用程序)。
将来,利用 echo
并打印所有变量和数组,以便您可以更好地了解正在发生的情况。
使用完整代码进行编辑:
我为您创建了一个示例,其中包含错误通知、更好地防止数据库注入(inject)(即使用带有 bind_param
的准备好的语句),以及在打印回 html 时转义外部数据。
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$answer = $_POST['answer']; // Set Post array from form to variables
$code = $_POST['code']; // Use could filter/validate here
$sid = $_POST['sid']; // I usually begin these variables with "dirty", "external", etc. so I remember not to trust it.
date_default_timezone_set('UTC');
$whenadded = date("Y-m-d H:i:s");
$user = "root";
$pass = "";
$host= "localhost";
$dbname="offlinesurvey";
$con = mysqli_connect($host,$user,$pass,$dbname);
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
}
$insert = mysqli_prepare($con, "INSERT INTO `lime_survery` (`sid`, `whenadded`, `code`, `answer`) values (?,?,?,?)");
echo mysqli_error($con);
mysqli_stmt_bind_param($insert, 'ssss', $sid, $whenadded, $code, $answer);
if (mysqli_stmt_execute($insert)){
// Be sure to escape external content!!!
echo '<p>The following values were received successfully:<br><br>SID: '.htmlspecialchars($sid).'<br>Code: '
.htmlspecialchars($code).'<br>User: '.htmlspecialchars($answer).'<br>Added: '.$whenadded.
'</p><p>You may submit a new survey response below.</p>';
}else{
echo mysqli_error($con);
}
mysqli_stmt_close($insert);
mysqli_close($con);
}
?>
<!DOCTYPE html>
<html lang="en-US">
<head><title>Lime Survey</title></head>
<body>
<h1>Lime Survery</h1>
<form method="POST">
<p>SID: <input type="text" name="sid" autofocus></p>
<p>Code: <input type="text" name="code"></p>
<p>Answer: <input type="text" name="answer"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
编辑2
这是我使用的数据库offlinesurvery中测试表的创建表SQL:
CREATE TABLE `lime_survery` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sid` varchar(100) NOT NULL,
`whenadded` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`code` varchar(255) NOT NULL,
`answer` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
关于php - 使用foreach向数据库插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45644913/