insert multiple rows into mysql table using php array

Posted by w3diy - 4 months ago

How to Insert multiple rows via a PHP array into MYSQL?

Example of an array with products $product:

Array
(
    [0] => Array
        (
            [ID] => 100
            [product_name] => Iphone
            [product_price] => 8.50
        )

    [1] => Array
        (
            [ID] => 101
            [product_name] => Computer
            [product_price] => 1.22
        )

    [2] => Array
        (
            [ID] => 102
            [product_name] => Laptop
            [product_price] => 0.90
        )
)

Now the function to insert into MYSQL:

$sql = array(); 

foreach( $product as $row ) {
    $sql[] = '('.$row['ID'].', "'.mysql_real_escape_string($row['product_name']).'",
    "'.$row['product_price'].'")';
}

mysql_query('INSERT INTO table (ID, product_name,product_price) VALUES '.implode(',', $sql));