dpdx51205 2018-04-27 12:38
浏览 35
已采纳

PHP表单在数据库中添加行[重复]

This question already has an answer here:

I am trying to INSERT data into a database from a PHP form. I have written the code below but I do not understand why everytime I refresh the form it adds a new row with the previously entered data into my Database. If someone could help me fix this issue, please.

<! DOCTYPE html>

<html>
<head>

<style>
.error {color: #FF0000;}
</style>
</head>

<body>  

<?php include 'config.php'; ?>


<?php


     if(isset($_POST['submit'])) {
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $addr = $_POST['addr'];
        $phone = $_POST['phone'];



    $query = "INSERT INTO `employee`(fname,lname,addr,phone) VALUES ('$fname','$lname','$addr','$phone')";
    $result = mysqli_query($con,$query) or die ("problem inserting new product into database");



     }


    ?>
    <h2>Sign Up</h2>
    <h3>Enter the data to Sign Up</h3>
    <p><span class="error">* required field</span></p>

    <form action = "" method = "post">
    Name: <input type = "text" name = "fname">
    <span class=error>*</span><br>
    Surname: <input type="text" name="lname">
    <span class=error>*</span><br>
    Address: <input type = "text" name = "addr">
    <span class=error>*</span><br>
    Phone Number: <input type = "tel" name="phone"><br>

    <input type = "submit" name="submit" value="Submit">
    </form>

</body>
</html>
</div>
  • 写回答

1条回答 默认 最新

  • dotn30471 2018-04-27 12:48
    关注

    When you validate a form, you create POST values in th eheader of your page. If you reload your page which has just undergone an action, it will repeat itself.

    Just after

    $result = mysqli_query($con,$query) or die ("problem inserting new product into database");
    

    You can add

    header('Location : nameofyourpage.php')
    

    or

    unset($_POST)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c51单片机控制步进电机
  • ¥20 Visual studio无法检测到设备
  • ¥15 为什么我通过html绘制的SVG折线图插入到word中坐标轴不显示出来
  • ¥30 vue 页面窗口放大或者缩小元素会变化
  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少