在我的数据库中,我有以下架构:
答案:
answerId(PK) auto_inc
answer
questionId
我将以下 JSON 字符串传递到我的 php 文件:
[{"answer":"bnk","questionId":"1"},{"answer":"1","questionId":"2"},{"answer":"b n","questionId":"3"},{"answer":"3","questionId":"4"},{"answer":"rgb","questionId":"5"},{"answer":"No","questionId":"6"},{"answer":"0","questionId":"7"},{"answer":"0","questionId":"8"},{"answer":"0","questionId":"9"},{"answer":"0","questionId":"10"},{"answer":"0","questionId":"11"},{"answer":"0","questionId":"12"},{"answer":"0","questionId":"13"},{"answer":"0","questionId":"14"},{"answer":"3","questionId":"18"},{"answer":"nko","questionId":"19"},{"answer":"hhkl","questionId":"15"},{"answer":"2","questionId":"16"},{"answer":"vnlf hugg","questionId":"17"}]
这是通过 $_POST['answers'] 中的发布请求捕获的:
if(isset($_POST['submitanswer'])){
$dbh = connect();
$user = $_POST['user'];
$entry = $_POST['entryId'];
$answers = $_POST['answers'];
$answers = json_decode($answers); //decode JSON answers
//for loop to iterate through answers ans insert new row into database
}
如何迭代答案数组并将新行插入到答案表中?
类似于:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES ($row['answer'], $row['questionId'])";
mysql_query($query);
}
最佳答案
如果此代码不适合您,请尝试以下操作:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES (".$row['answer'].", ".$row['questionId'].")";
mysql_query($query);
}
否则,我看不出这里有什么问题。
关于php - JSONKit - 将 JSON 字符串解析为 PHP 到 MYSQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6874489/