将JSON字符串保存到MySQL数据库 [英] Saving JSON string to MySQL database

查看:1371
本文介绍了将JSON字符串保存到MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON字符串

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 ?

我的PHP代码(我仅建立了与MySQL的连接,但无法保存记录)

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";

    ?>

推荐答案

我们将使用json_decode json_decode文档

也请务必逃脱!这是我在下面的操作方式...

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();

希望这会有所帮助!

这篇关于将JSON字符串保存到MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆