2

I've been working on this code and apparently each time i load the page it is inserting data to database.

<!DOCTYPE html>
<?php

include_once($_SERVER["DOCUMENT_ROOT"] .'/31783/functions.php');

$questions="";
$activityname="";
$myarray=array();

if($_SERVER["REQUEST_METHOD"] == "POST") {
    print_r($myarray);
    print_r($activityname);
    $questions = $_POST['myquestions'];
    $activityname = $_POST['activityname'];
    $myarray = array_filter(explode("|||", $questions));
    SqlRecord("INSERT INTO activity (name) VALUES ('$activityname')");
    foreach ($myarray as $value) {
        $connector = array();
        $connector = array_filter(explode("!!!", $value));
        $question = $connector[0];
        $answer = $connector[1];
        $activityid = SelectRecord("activity_id", "SELECT activity_id FROM activity WHERE name='$activityname'");
        SqlRecord("INSERT INTO question(activity_id,question,answer) VALUES (" . $activityid . ",'$question','$answer')");
    }
}
?>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery Add / Remove Table Rows</title>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <style type="text/css">

        tr:hover{
            cursor: move;
        }

    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
    var htm='<tr>\n' +
        '            <td><textarea name="name" required></textarea></td>\n' +
        '            <td><button class="remove"></button></td>\n' +
        '<td><select id="myAnswer" name="myAnswer" class="form-control"><option value="1">True</option><option value="2">False</option></select></td>'+
        '        </tr>';
        $(function () {
            $('tbody').sortable();

            $('#addRow').on( "click", function(){
                $('tbody').append(htm);
            });

            $(document).on('click','.remove',function(){
                $(this).parents('tr').remove();
            });

            $('#getValues').on( "click", function(){

                var myValues="";
                var values=[];
                $('textarea[name="name"]').each(function(i,elem){
                    values.push({
                        question:$(elem).val(),
                        answer:""
                    });
                });

                $('select[name="myAnswer"').each(function(i,elem) {
                    values[i].answer=$(elem).val();
                });

                for (var j=0;j<values.length;j++) {
                    myValues=myValues+values[j].question+"!!!"+values[j].answer+"|||";
            }

                //console.log(myValues);
                $("#myquestions").val(myValues);
            });

        });


    </script>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="container">

        <input type="text" id="activityname" name="activityname" required></br>
    <table>

        <tbody>
        <tr>
            <td><textarea name="name" required></textarea></td>
            <td><button class="remove"></button></td>
            <td><select name="myAnswer" class="form-control"><option value="1">True</option><option value="2">False</option></select></td>
        </tr>

        <tr>
            <td><textarea name="name" required></textarea></td>
            <td><button class="remove"></button></td>
            <td><select name="myAnswer" class="form-control"><option value="1">True</option><option value="2">False</option></select></td>
        </tr>
        </tbody>
    </table>

    <input id="getValues" type="submit" value="Submit"/>

    <input type="text" id="myquestions" name="myquestions">

    <button id="addRow">Add</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

</body>
</html>

I am not able to spot the error in the code. The code adds <tr> each time i press add. It transfer the values in <tr> to an array then it sends it as a string to an <input> in html to be able to read it in php and insert it in database. i didn't use ajax as the code is simple and straight forward.

Thank you

Karimb
  • 45
  • 5
  • 1
    If you click the Reload button after submitting the form, it will submit the form again. Browsers normally display a warning that this is happening and you have to confirm that you want it. – Barmar Nov 01 '18 at 01:14
  • @Barmar As you mentioned, i redirected the page to it self using header and it worked well. Thank you – Karimb Nov 01 '18 at 10:02

1 Answers1

0

if you replace

if($_SERVER["REQUEST_METHOD"] == "POST") {

for

if(isset($_POST['myquestions']) && !empty($_POST['myquestions'])) {

it should work, idk why your $_SERVER validation is not working, sorry

Pablo Cardozo
  • 103
  • 1
  • 10
  • Thank you for your message but it didn't work. The first time you load the page in a new tab it is fine and it works normally. when u want to refresh the page in the same tab it is reusing the previous data and keeps inserting in the database. Is there any way to solve this issue without redirecting the page to a new header? – Karimb Nov 01 '18 at 08:21
  • Why would this work any better? Clicking the reload button resubmits the form, so `$_POST['myquestions']` will be set again. – Barmar Nov 01 '18 at 15:51
  • 1
    BTW, it's not necessary to test both `isset` and `!empty`, just use `!empty`. The [documentation](http://php.net/manual/en/function.empty.php) says: **No warning is generated if the variable does not exist.** – Barmar Nov 01 '18 at 15:53