将API请求中的JSON数据插入MySQL数据库

时间:2018-06-08 01:50:38

标签: javascript php html mysql json

之前我发布了一个关于使用PHP将JSON数据传递到下拉菜单的类似问题。 How can i arrange data array from API request into HTML SELECT OPTION LIST?

现在我想将JSON数据插入MySQL数据库

下面是我的api_redcap.php代码,用于从其他Web服务器调用数据:

<?php 
     $data = array(
          'token' => '4B0D42AB9D061C0FADD724D2E908349D',
          'content' => 'report',
          'format' => 'json',
          'report_id' => '71',
          'rawOrLabel' => 'label',
          'rawOrLabelHeaders' => 'label',
          'exportCheckboxLabel' => 'false',
          'returnFormat' => 'json'); 

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://redcap-virtualbox/redcap/api/');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_VERBOSE, 0);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

curl_setopt($ch, CURLOPT_AUTOREFERER, true);

curl_setopt($ch, CURLOPT_MAXREDIRS, 10);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));

$output = curl_exec($ch);

$json = json_decode($output);    
?>

以下是我的api_redcap.php输出:

  

[{&#34; project_code&#34;:&#34; 16001&#34;,&#34; dept&#34;:&#34; Orthopedic Surgery(ORTHO)&#34;,&#34; group&#34;:&#34;&#34;,&#34; name&#34;:&#34; Jameson Lua Yao Chung&#34;},{&#34; project_code&#34;:&#34; 16002&#34;,&#34; dept&#34;:&#34; Rheumatology Allergy&amp;免疫学(RAI)&#34;,&#34; group&#34;:&#34;&#34;,&#34; name&#34;:&#34; Koh Ee Tzun&#34;},{& #34; project_code&#34;:&#34; 16003&#34;,&#34; dept&#34;:&#34;整形外科(ORTHO)&#34;,&#34; group&#34;:& #34;&#34;,&#34;名称&#34;:&#34; Ang Wei Luong&#34;},{&#34; project_code&#34;:&#34; 16004&#34;,&# 34; dept&#34;:&#34; Rheumatology Allergy&amp;免疫学(RAI)&#34;,&#34; group&#34;:&#34;&#34;,&#34; name&#34;:&#34; Lim Xin Rong&#34;},{& #34; project_code&#34;:&#34; 16005&#34;,&#34; dept&#34;:&#34;物理疗法(PT)&#34;,&#34; group&#34;:&# 34;&#34;,&#34;姓名&#34;:&#34;李坤曼&#34;}]

我的表名在MySQL数据库中称为PROJECT_CODE,属性如下:

  

表名 - PROJECT_CODE   字段名称:   PROJECT_code,   部门,   REQUESTOR,

我想将来自JSON的project_code,dept和name变量分别插入到MySQL表字段中。请帮忙。感谢

1 个答案:

答案 0 :(得分:0)

$json = json_decode($output, true);
foreach($json as $val)
{
    $project_code = $val['project_code'];
    $dept = $val['dept'];
    $name = $val['name'];

    /*
    * Generate insert query as below
    * "INSERT INTO MyGuests (project_code, dept, name) VALUES ($project_code, $dept, $name);";
    */

}

此外,您可以在单循环中插入多个记录 请查看以下参考链接 https://www.w3schools.com/php/php_mysql_insert_multiple.asp

在参考链接3中给出了不同的方法,因此,您可以使用任何适合您的方法