在php中的数据库中插入数组值

时间:2015-01-28 09:11:28

标签: php

我在print_r($ new_array);

时得到此输出
Array
 (
 [0] => Array
(
    [0] => A-I-only

    [1] => B-III-only

    [2] => C-I-and-II-only

    [3] => D-II-and-III-only

    [4] => E-I,-II,-III

)

[1] => Array
(
    [0] => A-Hepatitis-A

    [1] => B-Hepatitis-B

    [2] => C-Hepatitis-C

    [3] => D-Hepatitis-B-and-C

    [4] => E-None-of-the-above

)

[2] => Array
(
    [0] => A)-Cholestasis

    [1] => B)-Cholecystitis

    [2] => C)-Cholelithiasis

    [3] => D)-Hepatic-encephalopathy

    [4] => E)-Ascites

)
)

如何申请forloop在数据库中插入选项。

lyk我有桌子"答案"有字段" option_a"," option_b" ....." option_e"

我想将数组值存储在数据库中...第一行中的0数组...第二行中的1个数组..

1 个答案:

答案 0 :(得分:0)

您的意思是以下内容吗?

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO answers VALUES (?,?,?,?,?)");

foreach($new_array as $options){
    $stmt->bind_param('sssss',$option0,$option1,$option2,$option3,$option4);

    foreach($options as $key => $option){
        ${'option' . $key} = $option;
    }

    $stmt->execute();


}
$mysqli->close();

请求的mysql代码。 (如果某些字符串有逗号或类似字符串,则可能需要添加斜杠或使用mysql_escape_string)。即 $ {'选项'。 $ key} = mysql_escape_string($ option); 请注意,这已被弃用。)

foreach($new_array as $options){

    foreach($options as $key => $option){
        ${'option' . $key} = $option;
    }

    $query = "INSERT INTO answers VALUES ($option0,$option1,$option2,$option3,$option4)";

    mysql_query($query);

}