2012-02-15 84 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'] 
));