可能重复:
How can I prevent SQL injection in PHP?
Unable post text to MySQL using "Insert Into"
使用PHP将Movie标题传递到MySQL数据库时,我收到此错误:
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 's Dreams' )' at line 10
这是我的代码:
//Getting a list of all the users friends
$MyFriends=$facebook->api('/me/friends');
//Loop through friends array to identify each friend
$c=0;
while ($c<count($MyFriends['data']))
{
$N=$MyFriends['data'][$c]['name'];
$I=$MyFriends['data'][$c]['id'];
mysql_query("INSERT INTO UserFriends
(
UserFBID,
FriendFBID,
DisplayName
) VALUES
(
'$FBID',
'$I',
'$N'
) ") or die(mysql_error());
//Getting a list of friends each movie likes
$friendId = "/" . $I . "/movies";
$myFriendsMovies=$facebook->api($friendId);
//Loop through to identify each movie
$x=0;
while ($x<count($myFriendsMovies['data']))
{
$r = $myFriendsMovies['data'][$x]['id'];
$s = $myFriendsMovies['data'][$x]['name'];
mysql_query("INSERT INTO LinkedMovies
(
UserFBID,
MovieFBID,
MovieName
) VALUES
(
'$I',
'$r',
'$s'
) ") or die(mysql_error());
$x=$x+1;
}
$c=$c+1;
}
似乎变量$ s已经拍摄了电影'Akira Kurosawa's Dreams'并且继续轰炸,并出现上述错误。
答案 0 :(得分:1)
$N=$MyFriends['data'][$c]['name'];
应该是:
$N = mysql_real_escape_string($MyFriends['data'][$c]['name']); // sanitize the data, do this for all external data input
此外:
Please, don't use mysql_*
functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
答案 1 :(得分:1)
在执行sql查询之前,你应该使用像mysql_real_escape_string
函数之类的代码进行安全的sql查询和转义字符串
//Getting a list of all the users friends
$MyFriends=$facebook->api('/me/friends');
//Loop through friends array to identify each friend
$c=0;
while ($c<count($MyFriends['data']))
{
$N=mysql_real_escape_string( $MyFriends['data'][$c]['name'] );
$I=mysql_real_escape_string( $MyFriends['data'][$c]['id'] );
mysql_query("INSERT INTO UserFriends
(
UserFBID,
FriendFBID,
DisplayName
) VALUES
(
'$FBID',
'$I',
'$N'
) ") or die(mysql_error());
//Getting a list of friends each movie likes
$friendId = "/" . $I . "/movies";
$myFriendsMovies=$facebook->api($friendId);
//Loop through to identify each movie
$x=0;
while ($x<count($myFriendsMovies['data']))
{
$r = mysql_real_escape_string( $myFriendsMovies['data'][$x]['id'] );
$s = mysql_real_escape_string( $myFriendsMovies['data'][$x]['name']);
mysql_query("INSERT INTO LinkedMovies
(
UserFBID,
MovieFBID,
MovieName
) VALUES
(
'$I',
'$r',
'$s'
) ") or die(mysql_error());
$x=$x+1;
}
$c=$c+1;
}