我的表正在页面重新加载时用空行更新

时间:2014-07-18 15:56:37

标签: javascript php mysql forms validation

我已经用表单和一些PHP / JavaScript代码做了一个基本的例子。我正在使用JavaScript验证表单,并使用PHP简单地更新MySQL表。

function checkForm(){
    var x = document.forms['form1']['first'].value;
    if(x=='' || x==null){
        alert('please finish all required fields');
        return false;
    }
    var y = document.forms['form1']['last'].value;
    if(y=='' || y==null){
        alert('please finish all required fields');
        return false;
    }
    var z = document.forms['form1']['email'].value;
    if(z=='' || z==null){
        alert('please finish all required fields');
        return false;
    }   
    var a = document.forms['form1']['phone'].value;
    if(a=='' || a==null){
        alert('please finish all required fields');
        return false;
    }   
}

</script>
</head>
<body>
<?php

$connect = mysqli_connect('localhost','colin','-koolio-','knoxprograms');
if(mysqli_connect_errno()){
    echo "Error " . mysqli_connect_error();
}


$first = mysqli_real_escape_string($connect, $_POST['first']);
$last = mysqli_real_escape_string($connect, $_POST['last']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$phone = mysqli_real_escape_string($connect, $_POST['phone']);

$sql = "insert into users(firstName, lastName, email, phone) VALUES('$first','$last','$email','$phone');";

mysqli_multi_query($connect, $sql);
?>

<form name="form1" method="post" action="fuckwithpage.php" onsubmit="return checkForm()">
First name: <input type="text" name="first"><br>
Last Name: <input type="text" name="last"><br>
email: <input type="text" name="email"><br>
phone: <input type="text" name="phone"><br>
<input type="submit" value="send">
</form>

提交表单时发生的JavaScript验证(单击提交按钮)会阻止我的表在表单的验证函数返回false时更新。但是,如果重新加载页面或加载页面时,我的表中会添加一个空行。 任何人都可以帮助我。

2 个答案:

答案 0 :(得分:2)

开始你的php:

if ($_POST) {  //[...your code, here...]  }

否则,每次加载页面时,都会触发该代码块 - 因为没有什么可以告诉它&#34;嘿,我们只是加载页面,还没有提交任何内容,所以什么都不做 - &#34; - 这是上述条件语句将填补的角色。

答案 1 :(得分:0)

    if (isset($_POST)){    
$first = mysqli_real_escape_string($connect, $_POST['first']);
$last = mysqli_real_escape_string($connect, $_POST['last']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$phone = mysqli_real_escape_string($connect, $_POST['phone']);

$sql = "insert into users(firstName, lastName, email, phone) VALUES('$first','$last','$email','$phone');";

mysqli_multi_query($connect, $sql);
}

尝试CMIIW:))