这里,我将动态数组值插入数据库表中。它将数据完美地插入到数据库表中。但是,我需要对此代码进行一些修改。它正在使用,
插入数据。但是,我想将数组值存储在一个单独的行中。
现在我有:
id field_name
1 aaa, bbb, ccc, ddd
但我需要:
id field_name
1 aaa
2 bbb
3 ccc
4 ddd
我怎样才能做到这一点?
$choose_general_rules = $_POST['choose_general_rules'];
$choose_no_of_questions = $_POST['choose_no_of_questions'];
$choose_mark_questions = $_POST['choose_mark_questions'];
$choose_question_name = $_POST['choose_question_name'];
$question = array();
foreach($choose_question_name as $value) {
$question[] = $value;
}
$result_question = implode(',', $question);
$answer_1 = $_POST['answer_1'];
$answer_one = array();
foreach($answer_1 as $value) {
$answer_one[] = $value;
}
$result_answer_one = implode(',', $answer_one);
$answer_2 = $_POST['answer_2'];
$answer_two = array();
foreach($answer_2 as $value) {
$answer_two[] = $value;
}
$result_answer_two = implode(',', $answer_two);
$answer_3 = $_POST['answer_3'];
$answer_three = array();
foreach($answer_3 as $value) {
$answer_three[] = $value;
}
$result_answer_three = implode(',', $answer_three);
$answer_4 = $_POST['answer_4'];
$answer_three = array();
foreach($answer_3 as $value) {
$answer_three[] = $value;
}
$result_answer_three = implode(',', $answer_three);
try
{
$stmt = $dbh->prepare("INSERT INTO choose_the_correct_answer ( reference_id, general_rules, no_of_questions, mark_each_questions, question, answer_option_one, answer_option_two, answer_option_three, answer_option_four ) VALUES ( :ref_id, :choose_general_rules, :choose_no_of_questions, :choose_mark_questions, :choose_question_name, :answer_1, :answer_2, :answer_3, :answer_4 )");
$stmt->bindParam(':ref_id', $lastid, PDO::PARAM_INT);
$stmt->bindParam(':choose_general_rules', $choose_general_rules, PDO::PARAM_STR);
$stmt->bindParam(':choose_no_of_questions', $choose_no_of_questions, PDO::PARAM_STR);
$stmt->bindParam(':choose_mark_questions', $choose_mark_questions, PDO::PARAM_STR);
$stmt->bindParam(':choose_question_name', $result_question, PDO::PARAM_STR);
$stmt->bindParam(':answer_1', $result_answer_one, PDO::PARAM_STR);
$stmt->bindParam(':answer_2', $result_answer_two, PDO::PARAM_STR);
$stmt->bindParam(':answer_3', $result_answer_three, PDO::PARAM_STR);
$stmt->bindParam(':answer_4', $result_answer_three, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
echo "Error Inserting datas into database :" .$e->getMessage();
}
答案 0 :(得分:0)
您需要为插入执行循环才能获得多个插入。内爆也将数组转换为字符串。您需要循环数组并使用$ value变量作为bindParam()方法的输入参数。
您还要对变量进行双重初始化。
$answer_4 = $_POST['answer_4'];
$answer_three = array();
foreach($answer_3 as $value) {
$answer_three[] = $value;
}
上面的代码是
$answer_3 = $_POST['answer_3'];
$answer_three = array();
foreach($answer_3 as $value) {
$answer_three[] = $value;
}
$result_answer_three = implode(',', $answer_three);
添加的结果是逗号分隔的字符串。 implode使用demilmeter将数组转换为字符串。
你需要一个循环来插入数据x次,但你也需要遍历每个问题数组。没有完整的代码,我只能建议你。