PDO将简单的数组插入MySQL数据库 [英] PDO insert a simple array into MySQL database

查看:127
本文介绍了PDO将简单的数组插入MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,允许用户使用多个文本框添加不同的问题名称,然后将这些名称传递给数组:

I have a form which allows multiple text boxes for users to add different question names, these are then passed to an array:

name="question_name[]

我该如何使用PDO和MySQL将这个数组插入到我的问题表中?我已经尝试过:

How do i go about inserting this array into my questions table using PDO and MySQL? I have tried:

$sql = "INSERT INTO questions (`question_name`) VALUES (:question_name)";
$stmt = $db->prepare($sql);
$stmt->bindValue(':question_name', $question_name);
$stmt->execute();

这给了我

数组到字符串的转换"错误.

Array to string conversion" error.

我已经测试过print_r语句,并且结果符合预期:

I have tested the print_r statement and the results are as expected:

Array ( [0] => [Answer1] => [2] => [Answer2]) 

等...取决于使用的文本框数量.

etc... depending on the amount of text boxes used.

我知道这与BindValues/BindParam/execute()语句有关,我只是想要一个有效的正确方法和推理方法来帮助我学习.谢谢.

I understand that it is to do with BindValues / BindParam / execute() statement I would just like a correct method that works and reasoning to help me learn. Thanks.

推荐答案

简单解决方案:

$sql = "INSERT INTO questions (`question_name`) VALUES (:question_name)";
// prepare a stamemnt only once
$stmt = $db->prepare($sql);
$stmt->bindParam(':question_name', $question_name);
// iterate over your POST[question_name] array
foreach ($_POST['question_name'] as $question_name) {
    $stmt->execute();
}

这篇关于PDO将简单的数组插入MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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