2011-12-15 38 views
1

我得到了來自guardian api的響應,設法將它加載到變量中,我試圖將內容放入相關的數據庫表中,但它出現了以下錯誤:與PHP使用api時的SQL語法錯誤

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, "http://content.guardianapis.com/?format=json&show-  fields=all&show-related=true&order-by=newest&show-most-viewed=true&api- key=srty8vfmpgjhjakk4k6edbjb"); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($curl, CURLOPT_ENCODING, "gzip"); 
$response_api = curl_exec($curl); 
curl_close($curl); 

require_once 'Zend/Json.php'; 
$val = Zend_Json::decode($response_api); 
foreach ($val['response']['mostViewed'] as $result) { 
$title = $result['webTitle']; 
$url = $result['webUrl']; 
$body_text = $result['fields']['body']; 
$title = utf8_decode($title); 
$body_text = utf8_decode($body_text); 


$sql="INSERT INTO news_data (title, content) 
VALUES 
('$title','$body_text')"; 

if (!mysql_query($sql,$con)) 
    { 
    die('Error: ' . mysql_error()); 
} 
} 

mysql_close($con); 

?> 

我收到此錯誤的原因是,我試圖加載到某些變量文章中奇怪的字符,然後到我的數據庫?

感謝

JB

+1

可能重複的[mysql語法錯誤](http://stackoverflow.com/questions/6734004/mysql-syntax-error) – mario 2011-12-15 01:47:32

回答

1

試試這個

$sql="INSERT INTO `news_data` (`title`, `content`) 
VALUES 
('".mysql_real_escape_string($title)."','".mysql_real_escape_string($body_text)."')"; 
1

如果您使用的是過時的MySQL擴展和字符串連接,那麼你還需要在每個字符串變量適用mysql_real_escape_string()。那你的情況就是$title$body_text。否則,單個單引號將使您的INSERT查詢對MySQL服務器不可解析。 (和potential security issues,bla bla ...)