php – 将JSON字符串保存到MySQL数据库

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 将JSON字符串保存到MySQL数据库脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 JSON字符串
{"name":"jack","school":"colorado state","cITy":"NJ","id":null}

我需要将它保存在@L_777_3@中.我怎么能这样做?

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

<?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 documentation

也一定要逃脱!这是我将如何在下面做…

/* 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","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,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();

希望这可以帮助!

脚本宝典总结

以上是脚本宝典为你收集整理的php – 将JSON字符串保存到MySQL数据库全部内容,希望文章能够帮你解决php – 将JSON字符串保存到MySQL数据库所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。