简体   繁体   中英

Insert Json object to database in php

I am working on an android app which uses APIs made with php. Here, i am dynamically creating columns and their values.

I am verifying the API via postman and a strange thing happens every time, While looping through the Json Object what i am doing is first creating column and then inserting its values. The problem is only the 1st iteration saves the element and rest of them only creates the column but does not insert the values. I don't know if i am doing anything wrong, below is my php code.

<?php
include("connection.php");
$data = file_get_contents('php://input');
$json_data = json_decode($data);



    foreach($json_data as $key => $val) {
       $column_name = $key ;
      $c_column_name = preg_replace('/[^a-zA-Z]+/', '', $column_name);
       $column_value = $val ; 
       $table_name = "test2";
       $email = "ht@t.com";



    $result = mysqli_query($conn,"SHOW COLUMNS FROM $table_name LIKE '$c_column_name'");
    $exists = (mysqli_num_rows($result))?TRUE:FALSE;
     if($exists) {
        $query1 = "INSERT INTO  $table_name($c_column_name)VALUES('$column_value') ";
        $data0=mysqli_query($conn,$query);
           if($data0)
          {
           echo json_encode(array("success"=>"true - insertion","message"=>"Column existed, Successfully data sent.")); 
          }
          else{
          echo json_encode(array("success"=>"false - insertion","message"=>"Column existed,  data not inserted.")); 

          }
    }

    else{

      $query2="ALTER TABLE $table_name ADD COLUMN `$c_column_name` varchar(50) NOT NULL";

      $data1=mysqli_query($conn,$query2);
      if($data1){

         $query3="INSERT INTO  $table_name($c_column_name)VALUES('$column_value')";
          $data2=mysqli_query($conn,$query3);
          if($data2)
          {
          echo json_encode(array("success"=>"true - insertion","message"=>"Successfully data sent.")); 
          }
          else{
          echo json_encode(array("success"=>"false - insertion","message"=>"Column created but data not inserted.")); 

          }
      }

      else
      {
            echo json_encode(array("success"=>"false - column creation","message"=>"Failed to create column.'$column_name', '$table_name', '$conn'"));
      }
    }
    }
?>

Here is the Json Object through postman.

{"Shape":"rewq","Trans.No.":"yuuiop","Color":"qwert"}

Please help me with this, any help or suggestions are highly appreciated.

The second column name is Trans.No. which contains a dot, this is why it fails, probably you have an error as a result which prevents further columns from being created.

I think it would be much better to have a table with this structure:

attributes(id, key, value)

and whenever a key-value pair is received, you just insert/update it, depending on the logic you need to be executed. Your current model will create a separate row for each attribute, which is probably not what you want to achieve.

EDIT

Based on the information received in the comment section I reached the following conclusion:

You could create the missing columns first and then generate the insert statement with all the columns, having a single insert.

But it would be better to not create a separate column for each value, as the number of columns could quickly get out of hand. Instead you could have a table:

myentity(id, name)

for storing the entities represented by the JSON and

attributes(id, myentity_id, key, value)

for storing its attributes. This would be a neat schema with all the dinamicity you could want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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