Saving JSON string to MySQL database - php

I have a JSON string with me
{"name":"jack","school":"colorado state","city":"NJ","id":null}
I need it to be saved in the Database. How could i do this ?
My PHP code (I have only establish the connection to MySQL, but i am unable to save the records)
<?php
// the MySQL Connection
mysql_connect("localhost", "username", "pwd") or die(mysql_error());
mysql_select_db("studentdatabase") or die(mysql_error());
// Insert statement
mysql_query("INSERT INTO student
(name, school,city) VALUES(------------------------- ) ") // (How to write this)
or die(mysql_error());
echo "Data Inserted or failed";
?>

We'll use json_decode json_decode documentation
Also be sure to escape! here's how I would do it below...
/* create a connection */
$mysqli = new mysqli("localhost", "root", null, "yourDatabase");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* let's say we're grabbing this from an HTTP GET or HTTP POST variable called jsonGiven... */
$jsonString = $_REQUEST['jsonGiven'];
/* but for the sake of an example let's just set the string here */
$jsonString = '{"name":"jack","school":"colorado state","city":"NJ","id":null}
';
/* use json_decode to create an array from json */
$jsonArray = json_decode($jsonString, true);
/* create a prepared statement */
if ($stmt = $mysqli->prepare('INSERT INTO test131 (name, school, city, id) VALUES (?,?,?,?)')) {
/* bind parameters for markers */
$stmt->bind_param("ssss", $jsonArray['name'], $jsonArray['school'], $jsonArray['city'], $jsonArray['id']);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
Hope this helps!

This is example for help you
<?php
$json = '{"name":"jack","school":"colorado state","city":"NJ","id":null}';// You can get it from database,or Request parameter like $_GET,$_POST or $_REQUEST or something :p
$json_array = json_decode($json);
echo $json_array["name"];
echo $json_array["school"];
echo $json_array["city"];
echo $json_array["id"];
?>
Hope this help !

Decode into an array and pass it in your mysql_query, the code below is not using mysql_real_escape_string or any other means of security, which you should implement.
Assume $json is {"name":"jack","school":"colorado state","city":"NJ","id":null}
$json_array = json_decode($json);
You now have indexes in a php array, such as: $json_array['name']
mysql_query("INSERT INTO student (name, school,city) VALUES('".$json_array['name']."', '".$json_array['school']."', '".$json_array['city']."') ") or die(mysql_error());

Related

How do I insert simple rows of json data into a mysql table using PHP? [duplicate]

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.
$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.
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);
}
There is no such variable as $data. Try
$obj = json_decode($json,true);
Rest looks fine. If the error still persists, enable error_reporting.
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');
$string=mysql_real_escape_string($json);
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."));
}
}

PHP Security JSON

I have this PHP Script that receives data from an android Application. What Security methods are used to ensure that this PHP script is secure?! like isset function?!
<?php
require ('config.php');
$connection=mysqli_connect($servername,$username,$password,$db);
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$movie_name=$obj['movie_name'];
mysqli_query($connection,"insert into movie (movie_id, movie_name) VALUES (NULL,'$movie_name');");
echo "inserted";
?>
Thanks in advance.
I've edited your example code to check for connection / json_decode failing, and to make use of prepared statements. You might consider doing some validation on the movie name e.g. is it shorter than the length of the database field for example. However, the prepared statements should stop any SQL injection:
<?php
require ('config.php');
$connection=mysqli_connect($servername,$username,$password,$db);
if (!$connection) {
// mysql connection failed - error
exit();
}
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
if( $obj == null ) {
// json decode failed
exit();
}
$stmt = $connection->prepare("INSERT INTO movie (movie_id, movie_name) VALUES (NULL, ?)");
$stmt->bind_param('s', $obj['movie_name']);
$stmt->execute();
$stmt->close();
echo "inserted";

How to insert json array into mysql database

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.
$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.
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);
}
There is no such variable as $data. Try
$obj = json_decode($json,true);
Rest looks fine. If the error still persists, enable error_reporting.
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');
$string=mysql_real_escape_string($json);
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."));
}
}

Remove db $conn from MYSQLI query

I'm currently learning mysqli and systematically replacing all of my deprecated queries throughout my script.
I have this query:
<?php
$link = mysqli_connect("host", "user", "pass", "name");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM pins WHERE id='$pinDetails->id'";
$result = mysqli_query($link, $query);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$feature = $row['featured'];
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
Which I can echo throughout the page as <?php echo $row['date_featured']; ?>
My question is how do I rework the code to remove the connection? I don't want to keep connecting to the db in every query when I have a general connection include at the top of the page.
Actually you need connection for this page to operate based on your SQL database ,, can you explain more that what do you mean by removing connection
you can use INCLUDE();

Insert data into MySql table strange exception

I am using this code to insert some values in MySql table:
<?php
mysql_connect("localhost","root","root");
mysql_select_db("bib");
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query);
// Display an appropriate message
if ($result)
echo "<p>Product successfully inserted!</p>";
else
echo "<p>There was a problem inserting the Book!</p>";
mysql_close();
?>
After running it into browser, the following error occurs:
"Apache HTTP Server has encountered a problem and needs to close. We are sorry for the inconvenience."
It seems that mysql_select_db("bib") statement causes it. Database is create , also table...
I am running php 5.3 and mysql 5.1 on windows xp sp 2.
Please any ideas are welcomed...
Thanks...
Any of the mysql_* functions can fail for various reasons. You have to check the return values and if a function indicates an error (usually by returning FALSE) your script has to react appropriately.
mysql_error($link) and mysql_errno($link) can give you more detailed information about the cause. But you don't want to show all the details to just any arbitrary user, see CWE-209: Information Exposure Through an Error Message.
If you don't pass the connection resource returned by mysql_connect() to subsequent mysql_* functions calls, php assumes the last successfully established connection. You shouldn't rely on that; better pass the link resource to the functions. a) If you ever have more than one connection per page you must pass it anyway. b) If there is no valid db connection the php-mysql modules tries to establish the default connection which is usually not what you want; it only takes up more time to fail ..again.
<?php
define('DEBUGOUTPUT', 1);
$mysql = mysql_connect("localhost","root","root");
if ( !$mysql ) {
foo('query failed', mysql_error());
}
$rc = mysql_select_db("bib", $mysql);
if ( !$rc) {
foo('select db', mysql_error($mysql));
}
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query, $mysql);
// Display an appropriate message
if ($result) {
echo "<p>Product successfully inserted!</p>";
}
else {
foo("There was a problem inserting the Book!", mysql_error($mysql), false);
}
mysql_close($mysql);
function foo($description, $detail, $die=false) {
echo '<pre>', htmlspecialchars($description), "</pre>\n";
if ( defined('DEBUGOUTPUT') && DEBUGOUTPUT ) {
echo '<pre>', htmlspecialchars($detail), "</pre>\n";
}
if ( $die ) {
die;
}
}
try this to connect to database:
$mysqlID = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die("Unable to connect to database");
mysql_select_db(DB_DATABASE) or die("Unable to select database ".DB_DATABASE);
also, try this as your insert query:
$query = "INSERT INTO carte (id, title) values ('".$id."', '".addslashes($titlu)."')
$result = mysql_query($query) or die(mysql_error());
By using die(), it will tell you where it has failed and why

Categories