我遇到了令人困惑的問題 - 我正在設法從文本框中提取一個值,並將其成功插入到我的表中,但另一個(也來自文本框)是不會進入。在AJAX調用之前,我已經提醒我的數據串以確保兩個值都是正確的,而且它們是。然而,當我查看數據庫時,只輸入名稱值並且電子郵件空白。無法將一個項目導入到MySQL數據庫db
HTML:
<div id="basic-modal-content">
<h3>Please Alert me when this is Available</h3>
<p>Your Name: <input type="text" id="alert_name"/></p>
<p>Email Address: <input type="text" id="alert_email"/></p>
<button id="alert_submit">Submit</button>
</div>
的Javascript:
$('#alert_submit').click(function(){
var datastring = 'name='+ $('#alert_name').val() + '&email=' + $('#alert_email').val();
alert(datastring);
$.ajax({
type: "POST",
url: "process_email.php",
data: datastring,
success: function(data) {
}
});
alert ("We've received your request and will alert you once the directory is available. Thank you.");
$.modal.close();
});
PHP:
$name = $_POST['name'];
$email = $_POST['email'];
try {
$conn = new PDO('mysql:host=blah;dbname=blah', '-', '-');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO email_alerts(name, email) VALUES(':name, :email)");
$stmt->execute(array('name' => $name, 'email' => $email));
//$affected_rows = $stmt->rowCount();
$conn = null;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$conn = null;
}
'$ stmt-> EXE數組('name'=> $ name,'email'=> $ email));'應該是'$ stmt-> execute(array(':name'=> $ name,':email'=> $電子郵件));' –
@NullPoiиteяPDO也接受沒有冒號的參數名稱,雖然沒有記錄。 – Barmar
@Barmar yupp我知道,這就是爲什麼我用_shuold_而不是_must_ .. :) –