我有一个
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
原文链接:https://www.f2er.com/php/132924.html也一定要逃脱!这是我将如何在下面做…
/* 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();
希望这可以帮助!