Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中从关联数组向mysql数据库插入数据_Php_Mysql - Fatal编程技术网

在PHP中从关联数组向mysql数据库插入数据

在PHP中从关联数组向mysql数据库插入数据,php,mysql,Php,Mysql,我有以下关联数组 Array ( [0] => Array ( [0] => Liane Lanford [1] => Ken Christenson [2] => Melissa Jaramillo ) [1] => Array ( [0] => $310.40 [1] =&

我有以下关联数组

Array (
    [0] => Array
        (
            [0] => Liane  Lanford
            [1] => Ken Christenson
            [2] => Melissa Jaramillo
        )
    [1] => Array
        (
            [0] => $310.40
            [1] => $134.75
            [2] => $951.78
        )
    [2] => Array
        (
            [0] => $0.00
            [1] => $0.00
            [2] => $0.00
        )
    [3] => Array
        (
            [0] => $325.92
            [1] => $141.49
            [2] => $999.37
        )
    )
阵列中有3个客户。数字可以是4,5或更多。我想将数组中的数据插入数据库,如下表所示

如何编写foreach循环。我尝试了以下方法,但没有成功

foreach ($array as $payment_type => $payment) {
    foreach ($array[payment_type] as $pay => $value) {


        mysqli_query($link, "INSERT INTO table(name,subtotal,holdback,total) VALUES ('$pay[0]','$pay[1]','$pay[2]','$pay[3]') ");
    }
}

使用准备好的语句来防止SQL注入的一些代码:

$stmt = $link->prepare('INSERT INTO table(name,subtotal,holdback,total) VALUES (?, ?, ?, ?)');
foreach ($array[0] as $key => $value) {
    $stmt->bind_param('ssss', $value,  $array[1][$key], $array[2][$key],  $array[3][$key]);
    $stmt->execute();
}

您只需循环数组,然后使用索引访问子数组值中的所有其他值。我还使用了正确的准备和绑定机制来避免


您的脚本已打开。即使你应该考虑使用<代码> MySqLi<或<代码> PDO//COD> API,而不是级联值,我将在最后的脚本中使用。这只是样品检查。ThanksSide注意:您不应该将整数存储为纯文本。以后查询会比较困难。谢谢。它可以工作,但是查询运行了4次而不是3次
$stmt = $link->prepare("INSERT INTO table (name,subtotal,holdback,total) VALUES (?,?,?,?)");

foreach ($array[0] as $idx => $payment) {
    $stmt->bind_param('sdsd', $payment,
                              $array[1][$idx],
                              $array[2][$idx],
                              $array[3][$idx]
                );
    $stmt->execute();
}