我很难让这个看似简单的MySql查询正常工作。有人能发现问题吗?

<?php
include "config.php";

$offerid = $_POST["offerid"];
$ip = $_SERVER["REMOTE_ADDR"];

mysql_query("INSERT INTO voted (offerid,ip) VALUES (".$offerid.",".$ip.")");
?>

最佳答案

你可能想要一些单引号:

 "INSERT INTO voted (offerid,ip) VALUES ('" . $offerid . "','" . $ip . "')"

还应使用intvalmysql_real_escape_string来避免SQL注入漏洞:
 $sql = "INSERT INTO voted (offerid,ip) VALUES (" .
        intval($offerid). ", '" .
        mysql_real_escape_string($ip) . "')";

另一种可能更容易阅读的方法是使用sprintf
 $sql = sprintf("INSERT INTO voted (offerid, ip) VALUES (%d, '%s')",
                $offerid, mysql_real_escape_string($ip));

09-25 21:00