加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 16:29:48 所属栏目:PHP教程 来源:网络整理
导读:我有一个 JSON字符串 {"name":"jack","school":"colorado state","city":"NJ","id":null} 我需要将它保存在数据库中.我怎么能这样做? 我的PHP代码(我只建立了与MySQL的连接,但我无法保存记录) ?php // the MySQL Connection mysql_connect("localhost","use
我有一个 JSON字符串
{"name":"jack","school":"colorado state","city":"NJ","id":null}

我需要将它保存在数据库中.我怎么能这样做?

我的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: %sn",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();

希望这可以帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读