php - Inserting parts of a multidimensional array into a mysql database -
below portion of array returned magento api call. how able loop through records , insert values of parent_id, base_price, sku, , name keys mysql database:
$testarray
array(2) { [0]=> array(5) { ["store_id"]=> string(1) "1" ["base_grand_total"]=> string(3) "200" ["invoice_id"]=> string(1) "3" ["order_increment_id"]=> string(1) "2" ["items"]=> array(5) { ["parent_id"]=> string(1) "1" ["base_price"]=> string(8) "1400.000" ["tax_amount"]=> string(8) "120.2300" ["sku"]=> string(8) "testsku1" ["name"]=> string(9) "testprod1" } } [1]=> array(5) { ["store_id"]=> string(1) "1" ["base_grand_total"]=> string(3) "300" ["invoice_id"]=> string(1) "4" ["order_increment_id"]=> string(1) "3" ["items"]=> array(5) { ["parent_id"]=> string(1) "2" ["base_price"]=> string(8) "1000.000" ["tax_amount"]=> string(8) "100.5400" ["sku"]=> string(8) "testsku2" ["name"]=> string(9) "testprod2" } } } here have code far:
foreach ($testarray $row) { mysqli_query($con, "insert order_sku (parent_id, base_price, tax_amount, sku, name) values ('$row[parent_id]', '$row[base_price]', '$row[tax_amount]', '$row[sku]', '$row[name]')"); }
you using mysqli_ functions, please take advantage of using prepared statements. need use foreach loop inside access items index values. example:
$testarray = array( array( 'store_id' => '1', 'base_grand_total' => '200', 'invoice_id' => '3', 'order_increment_id' => '2', 'items' => array('parent_id' => '1', 'base_price' => '1400.000', 'tax_amount' => '120.2300', 'sku' => 'testsku1', 'name' => 'testprod1') ), array( 'store_id' => '1', 'base_grand_total' => '300', 'invoice_id' => '4', 'order_increment_id' => '3', 'items' => array('parent_id' => '2', 'base_price' => '1000.000', 'tax_amount' => '100.5400', 'sku' => 'testsku2', 'name' => 'testprod2') ), ); $con = new mysqli('localhost', 'username', 'password', 'database'); foreach($testarray $values) { foreach($values['items'] $item) { $stmt = $con->prepare('insert order_sku (parent_id, base_price, tax_amount, sku, name) values (?, ?, ?, ?, ?)'); // provided columns varchar $stmt->bind_param('sssss', $item['parent_id'], $item['base_price'], $item['tax_amount'], $item['sku'], $item['name']); $stmt->execute(); } }
Comments
Post a Comment