我正在尝试使用ajax将数据插入数据库。问题是除了在数据库中插入数据之外,一切都有效。 当我点击提交按钮时,我收到正确的消息"您已经订阅了#34; ,只是它没有在数据库中插入数据。并且不明白为什么。
我有dbconn.php
<?php
$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
?>
common-functions.php
<?php
require_once('dbconn.php');
function subscribe() {
global $db;
if(isset($_POST['semail'], $_POST['sname'])) {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($name)."', '".$db->escape_string($email)."', 0)");
echo "You have been subscribed";
}
}
subscribe();
?>
subscribe.php
HTML
<form name="subscribe" class="subscribe">
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail">
<input type="submit" id="ssub" value="Subscribe">
</form>
AJAX
<script type="text/javascript">
$(document).on('submit','.subscribe',function(e) {
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
</script>
答案 0 :(得分:4)
删除引号并在此处用反引号代替
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed')
^ ^