Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into table from Array PHP

Tags:

arrays

php

mysql

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

like image 798
Nehil Mistry Avatar asked Jul 19 '26 11:07

Nehil Mistry


2 Answers

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.

like image 91
Vegeta Avatar answered Jul 21 '26 01:07

Vegeta


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);

    }
like image 45
Priyank Avatar answered Jul 21 '26 00:07

Priyank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!