PHP运行一次并插入sql两次

时间:2016-12-09 17:56:26

标签: php html mysql sql forms

我的代码旨在从用户那里获取一个简短的文本和标题,并将它们添加到数据库中两次,并且无法理解原因。

   <?php ("session.php"); ?>
    <?php require_once("connect.php"); ?>
    <?php include("header.php"); ?>             

    <?php 


        //if the submit button is pressed then the INSERT SQL statement is submitted to database
        //if (isset($_POST['testimonial_title']) && isset($_SESSION['testimonial_text'])) {

        if(isset($_POST["submit_button"])){



            $title=$_POST["testimonial_title"];
            $text=$_POST["testimonial_text"];



            //create the sql statement 
            $sql=
                "INSERT INTO testimonials 
                (testimonial_title, testimonial_text, student_ID)
                VALUES(
                '$title',
                '$text',
                1);"; //for simplicity the student_ID is kept the same


            $result = mysqli_query($con,$sql);
            if(!mysqli_query($con, $sql))
            {
                echo "Journal entry was not entered successfully";
            }
            else{
                echo "Journal entry was entered successfully";
            }

             mysqli_close($con);
        }

    ?>


    <html>
        <body>

        <!-- Page Content -->
                    <h1 class="page-header">Learning Journals
                        <small>- Admin</small>
                    </h1>

                    <h3>Update Learning Journals Plans</h3>

                    <form name="membership_form" action= "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="contactForm"  method="post">

                        <label>Learning Journals Title:</label>
                        <br>
                            <input type="text" name="testimonial_title">
                        <br>

                            <label>Learning Journal:</label>
                            <br>
                            <textarea rows="10" cols="100" name="testimonial_text" maxlength="999" style="resize:none"></textarea>
                            <br>
                        <button type="submit" name ="submit_button" class="btn btn-primary">Update</button>
                    </form>
        </body>
    </html>

应该发生的事情是:

用户输入标题“xyz”

用户输入文字“xyz”

数据库接收:

ID | title | text | student_ID| 

1  | xyz   | xyz  | 1         | 

但相反,数据库看起来像这样:

ID | title | text | student_ID| 

1  | xyz   | xyz  | 1         | 

2  | xyz   | xyz  | 1         |

1 个答案:

答案 0 :(得分:5)

变化:

        $result = mysqli_query($con,$sql);
        if(!mysqli_query($con, $sql))

要:

        $result = mysqli_query($con,$sql);
        if(!$result)