[英]PHP Looping through elements and adding to Database
I don't know if what I'm trying to do is achievable / plausible but I'll ask anyway: 我不知道我想做的事是否可行/合理,但我还是会问:
I am building a survey type website and am looking at storing the responses in a MySQL DB. 我正在建立一个调查类型的网站,并正在考虑将响应存储在MySQL数据库中。 Each response / text field will be a record
每个回复/文本字段将是一条记录
The current page that I'm working on has two elements (Answer1 and Answer2). 我正在处理的当前页面有两个元素(Answer1和Answer2)。
How can I get the submit to add each answer as a separate line in my DB? 如何获得提交,以将每个答案作为单独的行添加到数据库中? eg, 2 separate records, with different text stored in the responsetext field?
例如,2条单独的记录,在responsetext字段中存储了不同的文本?
I have the below (obviously changed for security reasons), which adds one record, but of the element that I specify: 我有以下内容(出于安全原因而明显更改),它添加了一条记录,但是记录了我指定的元素:
$conn = new mysqli($dbhost, $dbuser, $dbpass,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO responses (qkey,rtext)
VALUES ('".$_POST["1"]."','".$_POST["Q1Answer"]."')");
$Q1Answer = $_POST["Q1Answer"];
$stmt->bind_param("s", $Q1Answer);
$stmt->execute();
$stmt->close();
$conn->close();
I imagine I could loop through all the elements and add them one by one? 我想我可以遍历所有元素并一一添加? Is this possible on the submit action / post?
在提交动作/帖子上可以吗?
I have searched here but can't find anything that has been able to help... 我在这里搜索过,但是找不到任何可以帮助的...
First of all, NEVER use $_POST or $_GET or $_SESSION values in your sql-statement, you should always sanitize with for example: 首先,切勿在sql语句中使用$ _POST或$ _GET或$ _SESSION值,您应始终使用以下方法进行清理:
$value = mysqli_real_escape_string($_POST['value1']);
This is to prevent any mysql injections just like OldPadawan mentions.. 就像OldPadawan提到的那样,这是为了防止任何MySQL注入。
To answer your question you could use a for loop: 要回答您的问题,您可以使用for循环:
$i = 1;
foreach ( $_POST as $key => $value ){
if ( $key == $i ){
$value.$i = mysqli_real_escape_string($value);
}
if ( $key == 'Q'.$i.'Answer' ){
$value.$i = mysqli_real_escape_string($value);
}
if ( $i % 2 ){
mysqli_query($conn, "INSERT INTO responses (qkey,rtext) VALUES ($key.($i-1), $key.$i)");
}
$i++;
}
look at this @K. 看看这个@K。 Tromp
战队
$i = 1;
$queryValue = NULL;
foreach ($_POST as $key => $value) {
if ($key == $i) {
$value . $i = mysqli_real_escape_string($value);
}
if ($key == 'Q' . $i . 'Answer') {
$value . $i = mysqli_real_escape_string($value);
}
if ($i % 2) {
$queryValue .= "($key.($i-1), $key.$i),";
}
$i++;
}
$query = 'INSERT INTO responses (qkey,rtext) VALUES ' . rtrim($queryValue);
mysqli_query($conn, $query);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.