PHP循环遍历元素并添加到数据库 [英] PHP Looping through elements and adding to Database

查看:67
本文介绍了PHP循环遍历元素并添加到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我正在尝试做的事情是否可以实现/合理,但我还是会问:

I don't know if what I'm trying to do is achievable / plausible but I'll ask anyway:

我正在构建一个调查类型的网站,并且正在考虑将响应存储在 MySQL 数据库中.每个响应/文本字段将是一个记录

I am building a survey type website and am looking at storing the responses in a MySQL DB. Each response / text field will be a record

我正在处理的当前页面有两个元素(Answer1 和 Answer2).

The current page that I'm working on has two elements (Answer1 and Answer2).

如何让提交将每个答案作为单独的一行添加到我的数据库中?例如,2 个单独的记录,在 responsetext 字段中存储了不同的文本?

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?

我有以下内容(显然出于安全原因进行了更改),它添加了一条记录,但属于我指定的元素:

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...

推荐答案

首先,永远不要在你的 sql 语句中使用 $_POST 或 $_GET 或 $_SESSION 值,你应该总是清理,例如:

First of all, NEVER use $_POST or $_GET or $_SESSION values in your sql-statement, you should always sanitize with for example:

$value = mysqli_real_escape_string($_POST['value1']);

这是为了防止任何 mysql 注入,就像 OldPadawan 提到的那样..

This is to prevent any mysql injections just like OldPadawan mentions..

要回答您的问题,您可以使用 for 循环:

To answer your question you could use a for loop:

$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++;
 }

这篇关于PHP循环遍历元素并添加到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆