我有一个动态列表,人们可以在其中添加类别,并且可以为每个类别添加问题。
此刻,我将整个列表的标题存储在数据库中,并且类别也都可以使用,但是我不知道如何存储问题。我将它们放在一个数组中,所以应该不难,但仍然无法正常工作。
这是我的数据库结构:
templates:
id - template id
title - name of list (template)
id_company (company list belongs to, irrelevant for this question)
questioncat:
id - id of category
title - name of category
tid - template id that the category belongs to
questions:
id - question id
question - the actual question
catid - category id that the questions belong to
使用当前的代码,我可以添加一个模板,其中包含与其链接的类别。我使用以下代码执行此操作:
$conn = new Connection;
$arr = $_POST['lijst'];
$companyid = $_POST['companyid'];
$store = [];
// pull off first arr element
$title = array_shift($arr);
// save title to store
$store['title'] = $title['name'];
// Insert template title and companyid
$inserttemplate = '
INSERT INTO templates (title, id_company) VALUES ("'.$conn->real_escape_string($title["value"]).'","'.$conn->real_escape_string($companyid).'")';
$inserttemplatecon = $conn->query($inserttemplate);
$lastinserted = $conn->inserted_id();
$currCat = '';
foreach($arr as $a) {
$val = $a['value'];
// handle category
if($a['name'] == 'category[]') {
// save cat name
$currCat = $val;
$insertcats = '
INSERT INTO questioncat (title, tid) VALUES ("'.$conn->real_escape_string($currCat).'", "'.$conn->real_escape_string($lastinserted).'")';
$insertcatscon = $conn->query($insertcats);
// init questions array
$store[$currCat] = [];
echo $store[$currCat];
}else {
// add question to question array
$store[$currCat][] = $val;
}
}
如果在添加一些示例类别/问题时打印数组$store
,这是示例结果:
Array
(
[title] => lijsttitle
[Category 1] => Array
(
[0] => Question 1
[1] => Question 2
[2] => Question 3
)
[Category 2] => Array
(
[0] => Question 1
)
[Category 3] => Array
(
[0] => Question 1
)
[Category 4] => Array
(
[0] => Question 1
[1] => Question 2
)
)
我尝试回显echo $store[$currCat];
来查看是否可以显示问题,但这是一个数组,因此只显示Array,如果我打印它,我只会看到Array()
。
如何将问题添加到数据库中,并为每个问题提供正确的类别ID?
{{1}中的var_dump
,如下所示:
$arr
答案 0 :(得分:0)
我认为这应该有所帮助
foreach($arr as $ar){
foreach($ar as $key=>$val){
if(($key=="name")&&($val=="category[]"))
//insert into category table here and retrieve its id(category Id)
elseif(($key=="name")&&($val=="question[]"))
//insert into questions table with the retrieved category Id.
}
}