2012-02-15 120 views
0

我正在使用WordPress,并在管理部分中创建了一个表单。我想提交给另一个数据库(不是默认的WP),所以我成功切换数据库并执行插入查询,但我一直收到错误。无法提交表单到数据库

这是我的代码:

$selected = mysql_select_db('petracms', $serverAccess); 
if (!$selected) { 
    die ('Can\'t use foo : ' . mysql_error()); 
} 
$query = "INSERT INTO `petra_customers` (`FirstName`, `LastName`, `Email`, `Phone`) VALUES ($fName, $lName, $email, $phone)"; 
$result = mysql_query($query); 
if (!$result) { 
    die('Invalid query: ' . mysql_error()); 
} 

我不断收到此错误:

Invalid query: 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 '@gmail.com, 5859475566)' at line 1

这是我输入:(Adam, Page, [email protected], 5859475566)

我不知道我做错了

+0

也许它将“@”解释为某种形式的正则表达式。这是我最好的猜测,而不了解PHP。尝试在“@”字符前面加上“\”字符。哦,如果可行,请考虑不使用内联变量。相反,将它们连接起来。例如:“values”。$ myVariableToInsert。“;” – 2012-02-15 07:58:49

回答

1

INSERT声明中的值需要包含在报价(除“数字”):

INSERT INTO `foo` (`a`,`b`,`c`) VALUES("foo","bar",1) 

这是你将如何(安全)构造一个变量在查询字符串插中使用(这是令人难以接受的,虽然):

$email = sprintf('"%s"', mysql_real_escape_string($_POST['email'])); 
$query = "INSERT INTO `foo` (`email`) VALUES($email)"; 

更优雅的方式(和更安全,太),是使用准备好的语句(例如使用PDO):

# Prepare the statement 
$sth = $dbh->prepare('INSERT INTO `foo` (`email`) VALUES(:email)'); 

# Substitute placeholders in query and execute it 
$sth->execute(array(
    'email' => $_POST['email'] 
));