2011-12-15 12 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

答えて

1

は、あなたが古いMySQL拡張と文字列連結を使用している場合、あなたはまた、各文字列変数にmysql_real_escape_string()を適用する必要があり、この

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

を試してみてください。あなたのケースでは$title$body_textです。それ以外の場合は、単一の単一引用符でINSERTクエリをMySQLサーバに対して解析不能にします。 (そしてpotential security issues、bla bla ...)

関連する問題