I have four Array consisting of some values. I want to insert Array with same index in same row. Eg:
$product = [Facebook, Twitter];
$sub_product = [Likes, Boost];
$plan = [10k, 20k];
$months = [3,6];
I want table to be some thing like this
+----+----------+-------------+------+--------+
| id | product | sub_product | plan | months |
+----+----------+-------------+------+--------+
| 1 | Facebook | Likes | 10k | 3 |
+----+----------+-------------+------+--------+
| 2 | Twitter | Boost | 20k | 6 |
+----+----------+-------------+------+--------+
What will be the best way to achieve this such that Index of each array falls in same row? I want to insert in HTML table
If you want to execute mysql_query in single shot then
$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);
This will be faster than executing multiple mysql_query function in a loop.
Try This Code,
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With