将数组插入2个单独的MySQL表 - PHP

时间:2015-04-28 09:58:22

标签: php

我需要协助将数组插入多个表中。

我的数组如下所示:

Array ( 
[customerId] => 4 
[DateCreated] => 2015-04-28 
[Description] => This is a test invoice 
[Amount] => 19.79
[invoiceline] => Array ( 
                   [0] => Array ( [description] => Product A [amount] => 5.00 ) 
                   [1] => Array ( [description] => Product B [amount] => 6.99 ) 
                   [2] => Array ( [description] => Product C [amount] => 7.80 ) 
                  ) 
)

我的2张表是:

发票 ID 顾客ID 描述 创建日期 量

INVOICELINES ID InvoiceId - (首先需要插入发票以获取插入的最后一条记录) 描述 创建日期 量

非常感谢任何协助。

2 个答案:

答案 0 :(得分:0)

您需要在第二次插入之前拆分数组:

这样做:

$dataArr = array("customerId" => 4,
    "DateCreated" => "2015-04-28",
    "Description" => "This is a test invoice",
    "Amount" => 19.79,
    "invoiceline" => array(
        array("description" => "Product A", "amount" => 5.00),
        array("description" => "Product B", "amount" => 6.99),
        array("description" => "Product C", "amount" => 7.80)
    )
);

$new_arr = $dataArr['invoiceline'];

$query1 = "INSERT INTO INVOICES (CustomerId, Description, DateCreated, Amount) VALUES ('".$dataArr['customerId']."', '".$dataArr['DateCreated']."', '".$dataArr['Description']."', '".$dataArr['Amount']."')" ;
$result1 = mysql_query($query1);

$last_insertid = mysql_insert_id();

foreach($new_arr as $narr){

$query1 = "INSERT INTO INVOICELINES  (InvoiceId, Description, Amount) VALUES ('".$last_insertid."', '".$narr['Description']."', '".$narr['Amount']."')" ;
$result1 = mysql_query($query1);
}

让我知道更多帮助!

答案 1 :(得分:0)

尽可能使用PHP PDO

使用' mysql' API已被劝阻多年了。虽然' mysqli'如果你愿意学习一种新的(并且我相信更好的)做事的方式,那么API对于那些过渡的人来说非常有用。“PDO' API真的是要走的路 http://php.net/manual/en/mysqlinfo.api.choosing.php

使用' PDO'准备好的语句消除了SQL注入攻击的可能性 提供了仅仅准备'查询一次。
http://php.net/manual/en/pdo.prepared-statements.php

使用事务消除了孤立记录的可能性。 IE:一次将数据插入多个表时是否会发生错误 http://php.net/manual/en/pdo.transactions.php

最后,使用(异常)try / catch块可以优雅地处理数据库连接错误 http://php.net/manual/en/language.exceptions.php

守则

<?php

// Your array.
$array = array('customerId' => 4,
               'DateCreated' => '2015-04-28',
               'Description' => 'This is a test invoice',
               'Amount' => 19.79,
               'invoiceline' => array(array('description' => 'Product A',
                                            'amount' => 5.00),
                                      array('description' => 'Product B',
                                            'amount' => 6.99),
                                      array('description' => 'Product C',
                                            'amount'=> 7.80)
                                     ) 
              );

// Set your database connection details.
$db_host = 'localhost';
$db_name = 'your_db_name';
$db_username = 'your_db_username';
$db_password = 'your_db_password';

// Create the database connection handle (using mysql).
try {
    $dbh = new \PDO('mysql:host=' . $db_host . ';dbname=' . $db_name, $db_username, $db_password);
} catch (\Exception $e) {
    // If it failed let the user know.
}

// Insert the data.
try {
    // Begin the transaction.
    $dbh->beginTransaction();

    // Insert data into the 'INVOICES' table.
    $stmt = $dbh->prepare('INSERT INTO INVOICES (CustomerId, DateCreated, Description, Amount)  
                           VALUES (:customerId, :DateCreated, :Description, :Amount)');
    $stmt->bindParam(':customerId', $array['customerId'], PDO::PARAM_INT);
    $stmt->bindParam(':DateCreated', $array['DateCreated'], PDO::PARAM_STR);
    $stmt->bindParam(':Description', $array['Description'], PDO::PARAM_STR);
    $stmt->bindParam(':Amount', $array['Amount'], PDO::PARAM_INT);
    $stmt->execute();

    // Get the last inserted id.
    $last_id = $dbh->lastInsertId();

    // Insert data into the 'INVOICELINES' table.
    $stmt = $dbh->prepare('INSERT INTO INVOICELINES (InvoiceId, Description, DateCreated, Amount)  
                           VALUES (:InvoiceId, :Description, :DateCreated, :Amount)');
    $stmt->bindParam(':InvoiceId', $last_id, PDO::PARAM_INT);  
    $stmt->bindParam(':Description', $description, PDO::PARAM_STR);  
    $stmt->bindParam(':DateCreated', $array['DateCreated'], PDO::PARAM_STR);  
    $stmt->bindParam(':Amount', $amount, PDO::PARAM_INT);  

    foreach ($array['invoiceline'] as $key => $value) {
        $description = $value['description'];
        $amount = $value['amount'];
        $stmt->execute();
    }

    // Commit the transaction.
    $dbh->commit();
} catch (\Exception $e) {
    // If it failed, rollback the transaction and let the user know.
    $dbh->rollBack();
}

我希望这会有所帮助。

PS:记住,不要停止学习......