我有四个由一些值组成的数组.我想在同一行中插入具有相同索引的Array.例如:
$product = [Facebook, Twitter]; $sub_product = [Likes, Boost]; $plan = [10k, 20k]; $months = [3,6];
我希望桌子是这样的东西
+----+----------+-------------+------+--------+ | id | product | sub_product | plan | months | +----+----------+-------------+------+--------+ | 1 | Facebook | Likes | 10k | 3 | +----+----------+-------------+------+--------+ | 2 | Twitter | Boost | 20k | 6 | +----+----------+-------------+------+--------+
实现这一目标的最佳方法是什么,使每个数组的索引属于同一行?我想在HTML表中插入
如果你想在单发中执行mysql_query那么
$product = [Facebook, Twitter]; $sub_product = [Likes, Boost]; $plan = [10k, 20k]; $months = [3,6]; $query = 'insert into TABLE (product,sub_product,plan,months) values'; foreach( $product as $index => $col ){ $query .= "( '".$product[$index]."', '".$sub_product[$index]."', '".$plan[$index]."', ".$months[$index]." ),"; } $query = rtrim( $query, ','); mysqli_query(mysql_query);
这比在循环中执行多个mysql_query函数要快.
试试此代码,
foreach($product as $key=>$p){ $data = array( 'product'=>$p, 'sub_product'=>$sub_product[$key], 'plan'=>$plan[$key], 'months'=>$months[$key] ); //Code to insert this array to Database // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); $sql = "INSERT INTO `table`('product','sub_product',...) VALUES ($data['product'],$data['sub_product'],...)"; mysqli_close($conn); //OR If you are using Codeigniter, $this->db->insert('table',$data); }