我的代码将用户输入存储在HTML文件中,并将其保存到数据库中,然后以表的形式输出该数据库。但是由于某种原因,每次我添加候选者时,代码都会不断添加空白列,有时不仅是1或2,还包括多达6个空白列。我对如何避免这种情况完全不知所措。
我的代码在下面,我将HTML值传递到PHP文件:
function passName() {
$.ajax(
{
type: 'POST',
url: 'eDBase.php',
data: {first_name: first_name, last_name: last_name, email: email },
success: function(){
alert('Success');
}
});
}
PHP写入SQL数据库:
$fname = $_POST['first_name'] ?? '';
$lname = $_POST['last_name'] ?? '';
$email = $_POST['email'] ?? '';
$arraypass = "INSERT INTO clientinfo(First_Name, Last_Name, Emails)
VALUES('$fname','$lname','$email')";
if($conn->query($arraypass)){
echo'Candidate has been added';
}
else{
echo 'Error thrown while adding candidate to database';
}
if($conn->query($id)){
}
mysqli_close($conn);
任何理由都写空格吗?也许该写被反复调用了?
似乎您可以多次单击“提交”按钮,这就是为什么您有重复的记录。
https://stackoverflow.com/a/15640896/8173264
并确保电子邮件在数据库中是唯一的。
首先,如果它们不为空,请使用if语句验证您的值!
可能您的值没有传递给php,请逐步阅读教程。
Ajax,我使用序列化
$(document).ready(function(){
$('#ContactForm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"eDBase.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html(data.error);
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
$('#ContactForm')[0].reset();
}
}
});
});
});
PHP部分验证并将错误发送回ajax:
$error = array();
if(empty($_POST['first_name'])){
//Echo or create error you capture by ajax
$error .= "<p class='error'>Empty first_name.</p>";
}
if(empty($_POST['last_name'])){
//Echo or create error you capture by ajax
$error .= "<p class='error'>Empty last_name.</p>";
}
if(empty($_POST['email'])){
//Echo or create error you capture by ajax
$error .= "<p class='error'>Empty email.</p>";
}
//I use prepared statements to prevent from sql injections
if($error === ''){
$stmt = $conn->prepare("INSERT INTO clientinfo (first_name, last_name, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $_POST['first_name'], $_POST['last_name'], $_POST['email']);
if($stmt->execute()){
$error .= "<p class='success'>Records added succesfuly.</p>";
}
$stmt->close();
}
$data = array(
'error' => $error
);
echo json_encode($data);