2016-11-28 81 views
-1

这是我的代码:尝试插入JSON字符串WPDB与

$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 
    ) 
); 

我不能插入上面我的查询数据。

如果我更改变种$output,如$output = 1,它的工作原理是完美的。但不是用json字符串。

有没有把json字符串插入数据库与wordpress的技巧?

回答

-1

我发现了这个问题。

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

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

0

你需要逃避JSON或序列化的字符串,而插入JSON字符串从像下面的WordPress数据库..

$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 
    ) 
); 
+0

感谢您的回答。但它不起作用。 – cgee

0

你应该使用mysql_real_escape_string功能将它们存储到数据库之前转义字符。

$output = mysql_real_escape_string($output); 
+0

感谢您的回答。但它不起作用。 – cgee

+0

您可以在脚本的顶部添加以下几行来查看实际错误:error_reporting(E_ALL);函数ini_set( '的display_errors',1); – Techroshni

+0

我发现了这个问题。 我的数据库中的字段只有一个varchar(255)。 – cgee