2014-07-18 67 views
0

我已經用表單和一些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

開始你的PHP搭配:

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

否則,每次頁面加載時間,代碼塊將火 - 因爲沒有什麼告訴它:「嘿,我們只是加載頁面,什麼事都沒有已經提交,所以不要做任何事情 - 「 - 這是上述條件陳述將填補的角色。

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 :))

相關問題