16

Hi I'm trying to insert the json array into my MySQL database. I'm passing the data form my iphone there i have converted the data into json format and I'm passing the data to my server using the url its not inserting into my server.

This is my json data.

[{"name":"0","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"13123123","phone":"sdfsdfdsfsd","city":"sdfsf","email":"13123123"}]

This is my Php code.

<?php 

 $json = file_get_contents('php://input');
 $obj = json_decode($data,true);

 //Database Connection
require_once 'db.php';

 /* insert data into DB */
    foreach($obj as $item) {
       mysql_query("INSERT INTO `database name`.`table name` (name, phone, city, email) 
       VALUES ('".$item['name']."', '".$item['phone']."', '".$item['city']."', '".$item['email']."')");

     }
  //database connection close
    mysql_close($con);

   //}
   ?>

My database connection code.

   <?php

       //ENTER YOUR DATABASE CONNECTION INFO BELOW:
         $hostname="localhost";
         $database="dbname";
         $username="username";
         $password="password";

   //DO NOT EDIT BELOW THIS LINE
     $link = mysql_connect($hostname, $username, $password);
     mysql_select_db($database) or die('Could not select database');
 ?> 

Please tell where I'm doing wrong in the above code basically I'm not a php developer I'm mobile application developer so I'm using the php as a server side scripting please tell me how to resolve this problem.

7
  • 1
    Also show us the content of db.php. Commented Mar 20, 2014 at 4:34
  • Your code looks good i.e. parsing JSON and insert query I suppose its related to connection and db select. Use mysql_error() after the query to see what happened. Commented Mar 20, 2014 at 4:37
  • I think you have problem with the connection. As Amit said, show your db.php code Commented Mar 20, 2014 at 4:37
  • use error_reporting(E_ALL); Commented Mar 20, 2014 at 4:42
  • @amit have updated my db connection code in my question pls check it Commented Mar 20, 2014 at 4:42

6 Answers 6

16
 $json = file_get_contents('php://input');
 $obj = json_decode($json,true);

I think you are passing the wrong variable. You should pass $json in json_decode as shown above.

Sign up to request clarification or add additional context in comments.

Comments

9

You are missing JSON source file. Create a JSON file then assign it to var data:

<?php

require_once('dbconnect.php');

// reading json file
$json = file_get_contents('userdata.json');

//converting json object to php associative array
$data = json_decode($json, true);

// preparing statement for insert query
$st = mysqli_prepare($connection, 'INSERT INTO users(firstname, lastname, gender, username) VALUES (?, ?, ?, ?)');

// bind variables to insert query params
mysqli_stmt_bind_param($st, 'ssss', $firstname, $lastname, $gender, $username);

// processing the array of objects
foreach ($data as $user) {
    $firstname = $user['firstname'];
    $lastname = $user['lastname'];
    $gender = $user['firstname'];
    $username = $user['username'];
    
    // executing insert query
    mysqli_stmt_execute($st);
}

1 Comment

What does this offer over the other two answers here?
3

There is no such variable as $data. Try

$obj = json_decode($json,true);

Rest looks fine. If the error still persists, enable error_reporting.

1 Comment

good catch !! even I tried his code locally but I had it correct while checking it so missed that completely that he was using wrong variable name !!
0

Its simple you can insert json datatype as below. reference link: click here for more details

insert into sgv values('c-106', 'admin','owner',false,'[{"test":"test"}, 
{"test":"test"}]',0,'pasds');

Comments

-3
$string=mysql_real_escape_string($json);

1 Comment

Can you explain your code further? What does it do, and what makes you think that it solves the problem?
-3
header("Access-Control-Allow-Origin: http://localhost/rohit/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

//files needed to connect to database
include_once 'config/database.php';
include_once 'objects/main.php';

//get Database connection
$database = new Database();
$db = $database->getConnection();

//instantiate product object
$product = new Product($db);

//get posted data
$data = json_decode(file_get_contents("php://input"));

//set product property values
$product->b_nm = $data->Business_Name;
$product->b_pno = $data->Business_Phone;
$product->b_ads = $data->Business_Address;
$product->b_em = $data->Business_Email;
$product->b_typ = $data->Business_Type;
$product->b_ser = $data->Business_Service;

$name_exists = $product->nameExists();

if($name_exists){

    echo json_encode(
            array(
                "success"=>"0",
                "message" => "Duplicate Record Not Exists."

            )
        );

}   else{

        if($product->b_nm != null && $product->b_pno != null && $product->b_ads != null && $product->b_em != null && $product->b_typ != null && $product->b_ser != null){

                if($product->create()){
                //set response code
                http_response_code(200);

                //display message: Record Inserted
                echo json_encode(array("success"=>"1","message"=>"Successfully Inserted"));
            }

        }   
        else{

            //set response code
            http_response_code(400);

            //display message: unable to insert record
            echo json_encode(array("success"=>"0","message"=>"Blank Record Not Exists."));
        }
    }

4 Comments

Can you explain your code further? How does it insert anything in the database?
@NicoHaase see edited code. database connection file is a in another folder
I don't think anybody can use your code without these additional files. And I haven't asked you to provide more code, but to provide an explanation - that's what enables other peope to learn from your answer
90%-100% of the code in this answer is irrelevant to the question. Anything that might be relevant appears to be buried in other files not shown here. Perhaps you didn't really understand the main point of the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.