8

我有一个 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";

    ?>
4

3 回答 3

17

我们将使用json_decode json_decode 文档

也一定要逃走!这就是我在下面的做法......

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

希望这可以帮助!

于 2012-07-04T00:59:21.993 回答
1

这是帮助您的示例

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

希望这有帮助!

于 2012-07-04T07:09:23.410 回答
0

解码成一个数组并将其传递到您的 mysql_query 中,下面的代码没有使用 mysql_real_escape_string 或您应该实施的任何其他安全手段。

假设 $json 是 {"name":"jack","school":"colorado state","city":"NJ","id":null}

$json_array = json_decode($json);

您现在在 php 数组中有索引,例如: $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());  
于 2012-07-04T00:07:26.580 回答