duandian8251 2014-07-18 15:56
浏览 49
已采纳

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

I have made a basic example with a form and some PHP/JavaScript code. I'm validating the form using JavaScript and using PHP simply to update MySQL table.

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>

The JavaScript validation that occurs when the form is submitted(submit button is clicked) prevents my table from being updated if my validation function for the form returns false. However if the page is reloaded or when i load the page, an empty row is added to my table. can anyone assist me with this.

  • 写回答

2条回答 默认 最新

  • dongpu2727 2014-07-18 15:59
    关注

    Begin your php with:

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

    Otherwise, every time the page is loaded, that block of code will fire - since there's nothing telling it "Hey, we're just loading the page, nothing has been submitted yet, so don't do anything - " - that is the role that the above conditional statement will fill.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类