将 api 与 PHP 结合使用时出现 SQL 语法错误
我收到了 Guardian api 的响应,设法将其加载到变量中,我试图将内容放入相关的数据库表中,但出现以下错误:
错误:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解要使用的正确语法
$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);
?>
我收到此错误是因为文章中存在奇怪的字符,我试图将其加载到某些变量中,然后加载到我的数据库中吗?
谢谢杰
比
I got a response from guardian api, managed to load it into a variable, I am attempting to put the content into the relevant database table, but it comes up with the error below:
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);
?>
Am I getting this error because there are strange characters within the article that I am trying to load into the certain variables and then onto my database?
Thanks
JB
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个
Try this
如果您使用过时的 mysql 扩展和字符串连接,那么您还需要应用
mysql_real_escape_string()
< /a> 每个字符串变量。在您的情况下,这是$title
和$body_text
。否则,单个单引号将使 MySQL 服务器无法解析您的 INSERT 查询。 (还有潜在的安全问题,等等……)If you are using the outdated mysql extension and string concatenation, then you also need to apply
mysql_real_escape_string()
on each string variable. That's$title
and$body_text
in your case. Otherwise a single single quote will make your INSERT query unparsable for the MySQL server. (And potential security issues, bla bla...)