Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

mysqli - How can I post an array of objects into mysql DB using php?

I am new to php and am trying to pass an array of objects into a MySQL table. I want to be able to accept input data from the UI and and send it through to my DB table as rows. Currently, I am sending the hard coded array data from my code as shown below:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");
header('Content-Type: application/json');

$mysqli = mysqli_connect("localhost", "root", "", "craftsillicon"); 

if ($mysqli->connect_error) {
   die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}

**$order_array = [   
    '0' => array('Reports'),
    '1' => array('Invoices'),
    '2' => array('Contacts'),
];** 

postArray($order_array, $mysqli); 

 function postArray($array, $mysqli)  
 {  
      if(is_array($array))  
      {  
           $values = array();  
           foreach($array as $row => $value)  
           {  
                $item_name = mysqli_real_escape_string($mysqli, $value[0]);                
                $values[] = "('$item_name')";  
           }  
           $sql = "INSERT INTO claims(name) VALUES";  
           $sql .= implode(', ', $values);          

           if ($mysqli = mysqli_query($mysqli,$sql)) {
            $rows= array();
            while($row = mysqli_fetch_assoc($mysqli))
             {
               $rows[] = $row;
             }
             echo json_encode($rows);
         } else{    
            echo json_encode(array('result'=>'fail'));
           }
      }
   }  
 ?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...