JSONKit - 将JSON String解析为PHP到MYSQL数据库

时间:2011-07-29 14:14:36

标签: php iphone mysql xcode json

在我的数据库中,我有以下架构:

数目:

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
}

如何遍历answers数组并在我的答案表中插入新行?

类似的东西:

foreach($answers as $row){
   $query = "INSERT INTO Answers (answer, questionId) VALUES ($row['answer'], $row['questionId'])";
   mysql_query($query);
}

2 个答案:

答案 0 :(得分:1)

如果此代码不适合您,请尝试以下操作:

foreach($answers as $row){
 $query = "INSERT INTO Answers (answer, questionId) VALUES (".$row['answer'].", ".$row['questionId'].")";
 mysql_query($query); 
}

否则,我在这里找不到任何错误。

答案 1 :(得分:0)

我猜你知道这一点,但要确保你的连接字符串是好的。

实际上这就是我的工作。可能对您有点信息,我也在SQL中进行所有连接,以便我可以轻松地注释掉测试字段。

$Link = mysql_connect( $Host , $User , $Password , $DBName);

if (!$Link) {
    die('Could not connect: ' . mysql_error());
}



$sql = "insert into table "
                ."("
                    ."hashfirstName".","
                    ."hashfamilyName".","
                    ."hashemailAddress"
                    .")"
                ."values ("
                    ."'$firstNameHashed'".","
                    ."'$familyNameHashed'".","
                    ."'$emailAddressHashed'"
                    .")";

mysql_select_db($DBName , $Link) or die("Database error in insertdata<br>"."Error #" . mysql_errno() . ": " . mysql_error());



            if(!mysql_query($sql , $Link))
            {
                $errors['sql'] = $sql; 
                $errors['DBName'] = $DBName;
                $errors['Link'] = $Link;
                $errors['status'] = "false"; //There was a problem saving the data;
                echo json_encode($errors);
            }
            else
            {
                $errors['status'] = "true";
                echo json_encode($errors);
            }; // if(!mysql_query( $DBName , $sql , $Link))