PHP json_encode一个数组&存储在mysql中返回

时间:2012-11-01 12:25:36

标签: php mysql json

我想在mysql中将php数组存储为JSON。为此,我有meeting_point_json列,其中type ='longtext'。

这是数组:

Array
(
    [1] => Array
        (
            [date] => 23/4/2012
            [meeting_time] => 23:04
            [meeting_place] => town hall
            [venue] => London
            [opponents] => Tigers
            [official_incharge] => Mr Putin
        )

    [2] => Array
        (
            [date] => 23/4/2050
            [meeting_time] => 13:04
            [meeting_place] => chief office
            [venue] => Kenya
            [opponents] => Peococks
            [official_incharge] => Mr Black
        )

    [3] => Array
        (
            [date] => dsad
            [meeting_time] => sadas
            [meeting_place] => jjjjj
            [venue] => jjjj
            [opponents] => dasds
            [official_incharge] => asad
        )

)

这是php代码:

$data = json_encode($_POST['team_meeting_pt']);
    $sql = "UPDATE yami_sub_team set meeting_point_json = $data where id = $subteam_id";
    if(mysql_query($sql)){
        exit("Done!");
    }else{
        die('Something went wrong, changes not saved. Error details: ' . mysql_error());
    }

它应该可以工作,但相反,我得到一个错误:

Something went wrong, changes not saved. Error details: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"1":{"date":"23\/4\/2012","meeting_time":"23:04","meeting_place":"town hall","ve' at line 1

知道我在这里做错了吗?

5 个答案:

答案 0 :(得分:1)

尝试使用此行代替您:

$sql = "UPDATE yami_sub_team SET `meeting_point_json`='".$data."' WHERE `id`='".$subteam_id."';";

答案 1 :(得分:1)

见: $data ".$data."变量随$subteam_id变化 和 ".$subteam_id."变量$string = mysql_query("SELECT DATA FROM ".$variable."");

记住sql查询只发送为字符串,而不是变量在那里... 并以你的方式编写PHP。始终用“..”和“..”

包装变量

“..”和“..”取决于你的条带包装: 例如: 如果这样的话 $string = mysql_query('SELECT DATA FROM '.$variable.''); 所以,你必须使用“..”包装! 如果是这样的话 {{1}} 所以,你必须使用'..'包装!

祝你好运的朋友

答案 2 :(得分:0)

应该是这样的:

$sql = "UPDATE yami_sub_team set meeting_point_json = '" . mysql_escape_string($data) . "'where id = $subteam_id";

您可以在此处详细了解该功能:http://php.net/manual/en/function.mysql-escape-string.php

答案 3 :(得分:0)

$data = "'" . mysql_escape_string(json_encode($_POST['team_meeting_pt'])) . "'";

第1行更改

答案 4 :(得分:0)

首先我会使用一个准备语句。并将结果绑定到它以避免所有的硬船。

$conn = new mysqli($servername, $username, $password, $dbname);
//replaced $data with ? for security reasons
$sql = "UPDATE yami_sub_team set meeting_point_json = ? where id = $subteam_id";
$stmt->$conn_prepare($sql);
//binds data to the ?
// the 's' states string is replacing  ?
$stmt->bind_param('s',$data);
if($stmt->execute()){
{
     exit("Done!");
}else{
    die('Something went wrong....);
}