1
我知道解析JSON數據已經討論過很多,但我想可能是稍微簡單插入JSON數據到MySQL表
我需要一點點的編輯到bleow PHP腳本轉換JSON數據的工作,並將它推到MySQL表 ,因爲腳本只能讀取json數據! 我對PHP編碼不太熟悉。
任何幫助提前感謝。
<?php
$data_string = '{"para": {"psize":"1","date_offset":"now","lang":"en","page":1,"token":"class","subcat ":"15"},"req":"ne"}';
$ch = curl_init('http://exampe.com/websrv/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
header('Content-Type: text/plain; charset=utf-8');
print_r(json_decode($result));
?>
,結果我得到
stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[is_fav] => 0
[is_new] => 1
[description] => Panasonic
[is_sold] => 0
[language] => en
[image] =>
[contact_no] => 55561112
[is_pinned] => 0
[user_adv_id] => 1234
[premium_tag] => 0
[keywords] =>
[title] => for sale Panasonic
[is_not_abusive] => 0
[announce_date] => 2015-01-01 02:33:33
[user_id] => 13
[price] => 20
[main_image] => Array
(
[0] => http://example.com/user_adv/123.jpg
[1] => http://example.com/user_adv/124.jpg
[2] => http://example.com/user_adv/125.jpg
)
[resize_image] => Array
(
[0] => http://example.com/user_adv/res/123.jpg
[1] => http://example.com/user_adv/res/124.jpg
[2] => http://example.com/user_adv/res/125.jpg
)
[type] => user
)
)
[pinned_ads] => 0
[total_pages] => 240
[current_page] => 1
[total_ads_count] => 240
)
確定現在我已經更新代碼,但仍然在插入數據時面臨的問題,我得到了這是
PHP Notice: Undefined variable: string in /var/www/xx.php on line 36
錯誤的錯誤行是從$查詢開始,這裏我的代碼
$result = curl_exec($ch);
$json = json_decode($result, true);
header('Content-Type: text/plain; charset=utf-8');
function mysqlconnect(){
global $db;
$db = mysqli_connect("localhost", "user_db","mypass","my_db");
if (!$db) {
echo "Error: Could not connect to the database " . print_r(oci_error());
exit;
}
}
function mysqlclose() {
global $db;
mysqli_close($db);
}
mysqlconnect();
$query = "INSERT INTO wdwd VALUES (0,'" . $db->real_escape_string($string) . "')";
$result = $db->query($query);
mysqlclose();
print_r($json);
?>
這是一個非常普遍的任務,我可以建議你谷歌你在這裏使用的標籤?如果您遇到困難,我很樂意提供幫助,但我知道,網絡上已有無數更好的資源比我自身更好。我會補充說,你可以補充說,你可以添加'mysqli'到你的搜索。參數化查詢是這類事情的首選方法。 – user2027202827
您可以將編碼的json字符串插入到mysql表中。將數據類型設置爲* text *。 –
使用json_decode($ output,true);以數組形式返回並將其插入到數據庫中 –