";您的SQL语法中有一个错误“;8777次中有70次发生


"You have an error in your SQL syntax" occurs 70 out of 8777 times

所以我有了这个脚本,它获取了一堆json文件并将它们发送到我的数据库。该脚本适用于8777个文件,但对于70个文件,我收到了以下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 'Shea', '', '190', '1981-4-30', 'Right', '106', '13', '25', '65', '39', '64', '61' at line 1

这是我正在使用的循环,我为长时间的查询道歉:

For($id=1; $id<=205600; $id++)
{
if (file_exists('data/players/'.$id.'.json'))
    {
        //read json file
        $json_file = file_get_contents('data/players/'.$id.'.json');
        $file_data = json_decode($json_file, true);
        //my super long query
        $query =  'INSERT INTO `db`.`table` (`id`, `first_name`, `last_name`, `common_name`, `height`, `dob`, `foot`, `club_id`, `league_id`, `nation_id`, `attribute1`, `attribute2`, `attribute3`, `attribute4`, `attribute5`, `attribute6`, `rare`, `rating`, `type`) VALUES ('''.$id.''', '''.$file_data['Player']['FirstName'].''', '''.$file_data['Player']['LastName'].''', '''.$file_data['Player']['CommonName'].''', '''.$file_data['Player']['Height'].''', '''.$dob.''', '''.$file_data['Player']['PreferredFoot'].''', '''.$file_data['Player']['ClubId'].''', '''.$file_data['Player']['LeagueId'].''', '''.$file_data['Player']['NationId'].''', '''.$file_data['Player']['Attribute1'].''', '''.$file_data['Player']['Attribute2'].''', '''.$file_data['Player']['Attribute3'].''', '''.$file_data['Player']['Attribute4'].''', '''.$file_data['Player']['Attribute5'].''', '''.$file_data['Player']['Attribute6'].''', '''.$file_data['Player']['Rare'].''', '''.$file_data['Player']['Rating'].''', '''.$file_data['Player']['ItemType'].''');';
        mysql_query($query);
        //record loop status
        if (mysql_error())
        {
            $error = mysql_error();
            echo $error.'<br/>';
            $errors ++;
        }
        else
        {
            $entries ++;
        }
    }
}

那么我该如何解决这个错误呢?

在将变量添加到查询之前,请对其使用mysql_real_escape_string

$commonName = mysql_real_escape($file_data['Player']['CommonName']);

然后在查询中使用$commonName

尽管您确实应该使用PDO。有关介绍,请参阅PDO的第一步。

转义SQL将大大有助于解决此问题。

如果你在生产中使用它,你很幸运你有这么多成功的交易。

一个固定的例子看起来更像这样:

$dbh = new PDO(...);
$stmt = $dbh->prepare('INSERT INTO `db`.`table` (`id`, `first_name`, `last_name`, ...)
  VALUES (:id, :Player_FirstName, :Player_LastName, ...)');
$stmt->bindParam(':id', $id);
$stmt->bindParam(':Player_FirstName', $file_data['Player']['FirstName']);
$stmt->bindParam(':Player_LastName', $file_data['Player']['LastName']);
// ... Etc...
// insert one row
$stmt->execute();