dongliuliu0385 2018-11-20 11:31
浏览 43

将带有问题和答案的数组存储到数据库中

I have the following array which can be added to dynamically (multiple categories and multiple questions belonging to that category) but I am struggling on how to add them to my database.

This is an example of how my array can look like:

Array
(
    [title] => lijsttitle
    [Category name] => Array
        (
            [0] => Question 1
            [1] => Question 2
        )

    [Category name 2] => Array
        (
            [0] => Question1
        )

)

I remove the title using array_shift my code looks like this:

$arr = $_POST['lijst'];

$companyid = $_POST['companyid'];

$store = [];

// pull off first arr element
$title = array_shift($arr);
// save title to store
$store['title'] = $title['name'];

$currCat = '';
foreach($arr as $a) {
  $val = $a['value'];
  // handle category
  if($a['name'] == 'category[]') {
    // save cat name
    $currCat = $val;
    // init questions array
    $store[$currCat] = [];
  }
  else {
    // add question to question array
    $store[$currCat][] = $val;
  }
}

I insert the title of my question list first inside my template table, but I have two other tables one for my questions and one for my categories.

// 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);

I know I can connect those using their id with the last inserted id. But how can I insert all category names into my category table and the same for questions in my questions table?

I am not sure how to get those values from my foreach loop.

So first insert a category name and immediately after insert all questions that belong to that category with category_id being the last inserted id (of the inserted category).

I've tried printing/echoeing multiple variables but I'm not sure how to get the result I need.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号