Wednesday, 30 March 2016

How to Enter PHP Array within MySQL Database



This post is newcomer tutorial of PHP and MySQL. In This blog we will study how to enter php array within mysql database table. This is really natural issue when we have various rows of input data that we need to inserting within mysql as row.We can execute really efficiently using php to add array within mysql database. When you are working on some eCommerce website and you have store multiple item order array into session and when buyer want to place final order then at that time multiple item order array want to insert into order table then at that time this things required and I want to insert php array into mysql table.

There are two ways we add php array into mysql table database.

1) Insert PHP Array within MySql Using repeated Insert Query.

2) Insert PHP Array within MySql Database by applying Single Insert Query



Source Code

array_insert.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $order_array = array(  
      "0"     =>     array("Mobile Phone", "1", "5000"),  
      "1"     =>     array("Power Bank", "1", "500"),  
      "2"     =>     array("Selfi Stick", "1", "250")  
 );  
 //Repetitive Insert command on each row  
 function option1($array, $connect)  
 {  
      if(is_array($array))  
      {  
           foreach($array as $row => $value)  
           {  
                $item_name = mysqli_real_escape_string($connect, $value[0]);  
                $qty = mysqli_real_escape_string($connect, $value[1]);  
                $price = mysqli_real_escape_string($connect, $value[2]);  
                $sql = "INSERT INTO tbl_order(item_name, qty, price) VALUES ('".$item_name."', '".$qty."', '".$price."')";  
                mysqli_query($connect, $sql);  
           }  
      }  
 }  
 option2($order_array, $connect); //Call Function  
 //Single Insert command by concatenating all array values into array  
 function option2($array, $connect)  
 {  
      if(is_array($array))  
      {  
           $values = array();  
           foreach($array as $row => $value)  
           {  
                $item_name = mysqli_real_escape_string($connect, $value[0]);  
                $qty = mysqli_real_escape_string($connect, $value[1]);  
                $price = mysqli_real_escape_string($connect, $value[2]);  
                $values[] = "('$item_name', '$qty', '$price')";  
           }  
           $sql = "INSERT INTO tbl_order(item_name, qty, price) VALUES ";  
           $sql .= implode(', ', $values);  
           mysqli_query($connect, $sql);  
      }  
 }  
 ?>  

0 comments:

Post a Comment