簡體   English   中英

從數組將值插入數據庫

[英]Insert values into database from arrays

我的PHP看起來像這樣:

for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {

            $rows[] = array(
                'ingredientamount'         => $ingredientQTY[$i],
                'ingredientType' =>  $measurements[$i],
                'ingredientname'        => $ingredientNAME[$i]
            );
            print_r($rows[$i]);
}

打印出這樣的數組:

Array ( 
[ingredientamount] => 34 
[ingredientType] => Centiliter 
[ingredientname] => CHicken ) 

Array ( 
[ingredientamount] => 26 
[ingredientType] => Grams 
[ingredientname] => Cheddar Cheese )

我的數據庫中有三個字段名稱,分別為Ingredientamount,fasitionType和Ingredientname,分別對應於分配給$ rows []的兩個數組。 因此,如果我可以使用數組,那么我的數據庫將如下所示:

  1. 成分數量=> 34,成分類型=>百升,成分名稱=>雞肉
  2. 成分數量=> 26,成分類型=>克,成分名稱=>切達干酪

我的問題是:如何使用代碼獲取$ rows [](這是一個多維數組)並將每一行插入到像我的數據庫中?

感謝所有幫助!

試試這個代碼:

<?php

$rows = array();
$rows[] = array('ingredientamount' => '34', 'ingredientType' => 'Centiliter', 'ingredientname' => 'CHicken' );
$rows[] = array('ingredientamount' => '26', 'ingredientType' => 'Grams', 'ingredientname' => 'Cheddar Cheese' );

$sql = "INSERT `myTableName` (`ingredientamount`,`ingredientType`,`ingredientname`) VALUES ";
$coma = '';
foreach ($rows as $oneRow) {
    $sql .= $coma."('".implode("','",$oneRow)."')";
    $coma = ', ';
}

$result = $db->query($sql);


?>

畢竟,您會在$sql得到類似的信息
INSERT `myTableName` (`ingredientamount`,`ingredientType`,`ingredientname`) VALUES ('34','Centiliter','CHicken'), ('26','Grams','Cheddar Cheese')
它只是草稿代碼,沒有實際需要的錯誤檢查或輸入控制,但是它給出了工作原理的想法。 我相信您可以自己添加其余所有內容。

編輯

感謝您的回答,但是Ingredientamount,fastentType和Ingredientname的值是動態的,所以我認為這行不通嗎?

根本不是問題。 只需更改此行
$sql = "INSERT `myTableName` (`ingredientamount`,`ingredientType`,`ingredientname`) VALUES ";
對此
$sql = "INSERT `myTableName` (`".implode('`,`',array_keys($rows[0]))."`) VALUES ";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM