繁体   English   中英

Json_decode返回空值-JSON对象到php数组

[英]Json_decode returning empty value - json object to php array

我有一个基本形式,用于在文本区域内以json格式存储(在客户端)值。 然后,我计划将这些值存储在mysql数据库中。 我正在使用json_decode将json对象放入常规的php数组中。 但是当我检查print_r($personArray) ,什么都没有。 因此,每次我提交表单时,由于php数组为空,因此没有任何内容存储在mysql数据库中。 如何将值存储在mysql数据库的文本区域中? 这是现场演示

if(isset($_POST['submit'])) {
$data = $_POST['data'];
echo $data;
$personArray = json_decode($data, true);
print_r($personArray);


      foreach($personArray as $key => $value){

          $main_role1 = ($value['main1'] == "true") ? 1 : 0;
          $main_role2 = ($value['main2'] == "true") ? 1 : 0;
          $person_fname = $value['firstName'];
          $person_lname = $value['lastName'];
          $person_phone = $value['phone'];

          $query_init2 = "INSERT INTO person (main_role1, main_role2, first_name, last_name, person_phone) VALUES (:main_role1, :main_role2,:person_fname,:person_lname, :person_phone);";
          $query_prep2 = $db_con->prepare($query_init2);
          $insert_result2 = $query_prep2->execute(array(
            "main_role1" => $main_role1,
            "nmain_role2" => $main_role2,
            "person_fname" => $person_fname,
            "person_lname" => $person_lname,
            "person_phone" => $person_phone
          ));

        }
      }

HTML

<textarea name="data" rows='5' cols='60'>

JSON对象

    [
    {
        "firstName": "Danny",
        "lastName": "LaRusso",
        "ciscoID": "123",
        "academyID": "1",
        "email": "test1@email.com",
        "phone": "(555) 121-2121",
        "fax": "(123) 123-4567",
        "contact_role": true,
        "netacadContact": true,
        "netacadStaff": false,
        "netacadSuccess": false,
        "instructor_role": false
    },
    {
        "firstName": "Sensei",
        "lastName": "Miyagi",
        "ciscoID": "456",
        "academyID": "1",
        "email": "test2@email.com",
        "phone": "(555) 444-2222",
        "fax": "(123) 123-4567",
        "contact_role": false,
        "netacadContact": false,
        "netacadStaff": false,
        "netacadSuccess": false,
        "instructor_role": true
    }
]

json_decode工作正常。 问题是当您将值绑定到SQL语句中时。

$insert_result2 = $query_prep2->execute(array(
    ":main_role1" => $main_role1,
    ":nmain_role2" => $main_role2,
    ":person_fname" => $person_fname,
    ":person_lname" => $person_lname,
    ":person_phone" => $person_phone
));

您应该在数组的键中包含“:”。

同样,在查询结束时,您不需要另一个;。

$query_init2 = "INSERT INTO person (main_role1, main_role2, first_name, last_name, person_phone) VALUES (:main_role1, :main_role2, :person_fname, :person_lname, :person_phone)";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM