【问题标题】:try to insert a json string with wpdb尝试使用 wpdb 插入 json 字符串
【发布时间】:2016-11-28 10:33:03
【问题描述】:

这是我的代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.openweathermap.org/data/2.5/weather?q=".$location.",de&lang=de&APPID=abc");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch); //JSON string
curl_close($ch);

//json_decode($output);
//serialize($output);

$table_name = $wpdb->prefix . 'dmd_weather';
$wpdb->insert(
    $table_name,
    array(
        'time' => current_time( 'mysql' ),
        'type' => 'wetter',
        'key' => $location, //<- normal string
        'value' => $output //<- json string
    )
);

我无法使用上面的查询插入数据。

如果我将 var $output 更改为 $output = 1 ,它会完美运行。但不是 json 字符串。

用wordpress将json字符串插入数据库有技巧吗?

【问题讨论】:

    标签: php json wordpress insert


    【解决方案1】:

    您需要在将 json 字符串从 wordpress 插入数据库时​​转义 json 或序列化字符串,如下所示..

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://api.openweathermap.org/data/2.5/weather?q=".$location.",de&lang=de&APPID=abc");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch); //JSON string
    curl_close($ch);
    
    //json_decode($output);
    //serialize($output);
    
    $final_output = mysql_real_escape_string($output); //<- final escaped string
    
    $table_name = $wpdb->prefix . 'dmd_weather';
    $wpdb->insert(
        $table_name,
        array(
            'time' => current_time( 'mysql' ),
            'type' => 'wetter',
            'key' => $location, //<- normal string
            'value' => $final_output //<- json string
        )
    );
    

    【讨论】:

      【解决方案2】:

      您应该使用mysql_real_escape_string 函数将字符转义,然后再将它们存储到数据库中。

      $output = mysql_real_escape_string($output); 
      

      【讨论】:

      • 您能否在脚本顶部添加以下行以查看实际错误:error_reporting(E_ALL); ini_set('display_errors',1);
      • 我发现了问题。我数据库中的字段只是一个 varchar(255)。
      【解决方案3】:

      我发现了问题。

      我数据库中的字段只是一个 varchar(255)。

      这对我的 json 字符串来说还不够。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-24
        • 2016-06-30
        • 1970-01-01
        相关资源
        最近更新 更多