PHP将带有stdclass的数组插入MySQL

时间:2016-04-08 23:07:00

标签: php arrays

#pragma comment(lib, "Ws2_32.lib")

这是一张热点凭证。

    array(115) {
  [0]=>
  object(stdClass)#3 (13) {
    ["_id"]=>
    string(24) "57074056e4b03cad2f940060"
    ["admin_name"]=>
    string(5) "ramil"
    ["code"]=>
    string(10) "3596495399"
    ["duration"]=>
    int(1440)
  }

  [1]=>
  object(stdClass)#4 (13) {
    ["_id"]=>
    string(24) "57074056e4b03cad2f94005f"
    ["admin_name"]=>
    string(5) "ramil"
    ["code"]=>
    string(10) "7860239069"
    ["duration"]=>
    int(1440)
  }
  }
  ..........
  ..........

我在将此插入数据库时​​遇到问题。我刚开始PHP,从API调用$ data。

这是数组$ data的成功内爆。

var_dump ($data); //sample output above.
  

如何循环和插入数据库。?

$array=array($data_convert);
$value=implode(" ",$array);
echo $value;

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

1 个答案:

答案 0 :(得分:0)

尝试这样的事情......

function insert_data($dataObj){

  foreach($dataObj as $data){

      if(is_object($data)){
          // return field values and name as string 
          //something like this- (sn, answer) VALUES ([value-1],[value-2])
          $fieldValueString = $this->_array_to_string($data);

          $queryString = "INSERT INTO <tablename> $fieldValueString";

          //Execute query
          return $this->_link->query($queryString ); 
      }
   }<!-- ./foreach -->
}

支持功能:

public function _array_to_string($array){
    //Fetch where condition in a string
    $string = "";

    if($array !="" && count($array) >0){ 
        //Fetch fileds
        $dataArrayField = array();
        //Fetch values
        $dataArrayValue = array();

        foreach($filedsValue as $field => $value){ 
           $dataArrayValue[] = $value; 
           $dataArrayField[] = $field; 
        }

    $string = "( ".implode(", ", $dataArrayField)." ) VALUES ( '".implode("', '", $dataArrayValue)."' )";
    }
    return $string;
}