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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制