0

much time is passed since last time here.

Hope you are all well and thanks in advance for your help.

So I'm working on a simple update, delete, add PHP page that modify MySQL database.

In this "admin" pages I have created a long form and inside I put a table that shows actual results extracted from database (there you can modify or delete singole voices) followed by another table that allow you to add new elements inside db.

I wanted to have a dynamic form for second table in order to make it a little bit more elegant so I added jQuery code for that purpose.

The two problems I'm finding and I'm not able to solve are:

(1) in one column of form/table cell I used two "radio" inputs to indicate availability, or not, of a products but, if I create an array of elements with the name "availableNew[ ]", all the radio elements have the same name so, when I add the new row to the form, radio voice selection switch from one input to another on different rows as it happens when you use many radio inputs with the same name (all radio inputs are seen as alternatives, not as different couple of inputs "yes/no" located on different rows) - sorry for horrible way of explaining problem but I was unable to find a clearer way to explain it;

(2) jQuery code used to add/delete new rows works great, but when I "submit" the form - with POST_[ ] command - page send only those input that weren't added with script (on the other hand I receive the data coming from the 1st row of the form).

To be more clear: I have created the first row of the table/form as a php echoed table/form, so only to add elements from the second row I uses jQuery script. Than, when I send/post data to PHP, I receive only the first value of the array (corresponding to the first row of the table/form) but not the others (corresponding to the jQuery added rows).

So here are parts of the code I'm using:

1st part (Jquery code)

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

<script>
    $(document).ready(function(){
        $("#add-row").click(function(){

                        var dataNew = $("#dataNew").val();
                        var data = $("#data").val();
                        var counter = $("#countN").val();
                        counter++;

                        var markup = "<tr><td class='count'>" + counter + "<input type='hidden' id='countN' name='numN[]' value='" + counter + "'></td><td class='data'>" + dataNew + "<input type='hidden' id='data' name='todayN[]' value=" + data + "></td><td class='prod'><input type='text' id='prod' name='prodN[]' placeholder='Nuovo prodotto'></td><td class='var'><input type='text' id='var' name='varN[]' placeholder='Varietà'></td><td class='img'><input type='text' id='img' name='imgN[]' placeholder='Inserisci url della foto'></td><td class='available'><label class='choice' for='avaYnew'><input type='radio' id='avaYnew' name='availableN[]' value='yes' > Sì</label><label class='choice' for='avaNnew'><input type='radio' id='avaNnew' name='availableN[]' value='no' > No</label></td><td class='rows'><input type='button' class='delete-row' id='delete-row' value='Rimuovi'></td></tr>";

                        alert(markup);

                        $("#addProds").append(markup);
        });

                $("#delete-row").live('click', function(event) {
                $(this).parent().parent().remove();
                });
    });
</script>

2nd part (PHP echo form/table code)

<?php
            echo "<div>";
            echo "<form action=" . htmlspecialchars($_SERVER['PHP_SELF']) . " method='POST'>";

      //MOSTRA I RISULTATI
      $sqlMag = "SELECT * FROM elencoprodotti WHERE DATA = (SELECT MAX(DATA) FROM elencoprodotti) ORDER BY DATA DESC, PRODOTTO ASC";
      $resultMag = $conn->query($sqlMag);

      $count = 0;

      if (!empty($resultMag) && $resultMag->num_rows > 0) {

                echo "<br>Prodotti presenti nel database (ultimo aggiornamento al " . date("d.m.Y", strtotime($rowTit[0]))."):</div>";
                echo "<table>";
                echo "<thead><tr>";
                echo "<th>DB-ID</th>";
                echo "<th>N.</th>";
                echo "<th>Data</th>";
                echo "<th>Prodotto</th>";
                echo "<th>Varietà</th>";
                echo "<th>Foto</th>";
                echo "<th>Disponibilità</th>";
                echo "<th>Cancella</th>";
                echo "</tr></thead>";

      // output data of each row
            while($rowMag = $resultMag->fetch_assoc()) {
                $count++;

                        $AvailYes = $AvailNo = '';

                        if ((($rowMag["AVAILABLE"])) == "yes") {
                            $AvailYes = "checked";
                            $AvailNo = "";
                        } else if ((($rowMag["AVAILABLE"])) == "no") {
                            $AvailYes = "";
                            $AvailNo = "checked";
                        }

                echo "<tr>
                        <td class='id'>" . stripslashes($rowMag["ID"]) . "<input type='hidden' id='id' name='id-" .  stripslashes($count) . "' value=" . stripslashes($rowMag["ID"]) . "></td>
                        <td class='count'>" . stripslashes($count) . "<input type='hidden' id='count' name='num-" .  stripslashes($count) . "' value=" . stripslashes($count) . "></td>
                        <td class='data'>" . date("d-m-Y", strtotime(stripslashes($rowMag["DATA"]))) . "<input type='hidden' id='data' name='today-" . stripslashes($count) . "' value=" . $data . "></td>
                        <td class='prod'><input type='text' id='prod' name='prod-" . stripslashes($count) . "' value=" . stripslashes($rowMag["PRODOTTO"]) . "></td>
                        <td class='var'><input type='text' id='var' name='var-" . stripslashes($count) . "' value=" . stripslashes($rowMag["VARIETA"]) . "></td>
                        <td class='img'><a id='single_image' href=" . stripslashes(base64_decode($rowMag['FOTO'])) . " title=".stripslashes($rowMag["PRODOTTO"])."&nbsp;".stripslashes($rowMag["VARIETA"]).">
                            <img id='imageprod' alt=".stripslashes($rowMag["PRODOTTO"])."&nbsp;".stripslashes($rowMag["VARIETA"])." src=" .stripslashes(base64_decode($rowMag['FOTO'])). "></a>
                            <br><input type='hidden' id='img' name='img-" . stripslashes($count) . "' value=" . stripslashes(base64_decode($rowMag['FOTO'])) . "></td>
                        <td class='available'>
                        <label class='choice' for='avaY'><input type='radio' id='avaY' name='available-" . stripslashes($count) . "' value='yes' $AvailYes> Sì</label>
                        <label class='choice' for='avaN'><input type='radio' id='avaN' name='available-" . stripslashes($count) . "' value='no' $AvailNo> No</label>
                        </td>
                        <td class='delete'>
                        <label class='choice' for='del'><input type='checkbox' id='del' name='del-" . stripslashes($count) . "' value='canc'> rimuovi</label></td>
                        </tr>";
              }
          echo "</table>";
                echo "<input type='hidden' id='count' name='maxrows' value=" . stripslashes($count) . ">";
                echo "<br>";

                $insN = 1;
                echo "<input type='hidden' id='insN' name='insN' value=" . stripslashes($insN) . ">";
                //$insN++;
                echo "<div>";
                echo "<br>Inserisci nuovi prodotti nel database:</div>";
                echo "<table id='addProds'>";
                echo "<thead><tr>";
                echo "<th>N.</th><th>Data</th><th>Prodotto</th><th>Varietà</th><th>Foto</th><th>Disponibilità</th><th>+/-</th>";
                echo "</tr></thead>";
                echo "<tr>";
                echo "<td class='count'>" . stripslashes($insN) . "<input type='hidden' id='count' name='numN[]' value=" . stripslashes($insN) . "></td>
                <td class='data'>" . date("d-m-Y", strtotime(stripslashes($data))) . "<input type='hidden' id='data' name='todayN[]' value=" . $data . "><input type='hidden' id='dataNew' name='todayNew[]' value=" . date("d-m-Y", strtotime(stripslashes($data))) . "></td>
                <td class='prod'><input type='text' id='prod' name='prodN[]' placeholder='Nuovo prodotto' value=''></td>
                <td class='var'><input type='text' id='var' name='varN[]' placeholder='Varietà' value=''></td>
                <td class='img'><input type='text' id='img' name='imgN[]' placeholder='Inserisci url della foto' value=''></td>
                <td class='available'>
                <label class='choice' for='avaYnew'><input type='radio' id='avaYnew' name='availableN[]' value='yes' > Sì</label>
                <label class='choice' for='avaNnew'><input type='radio' id='avaNnew' name='availableN[]' value='no' > No</label>
                </td>
                <td class='rows'><input type='button' class='add-row' id='add-row' value='Aggiungi riga'></td>
                </tr>
                </table>";
                echo "<input type='hidden' id='countN' name='insN' value=" . stripslashes($insN) . ">";
                //echo "<input type='hidden' id='countTotN' name='maxNewrows' value=" . stripslashes($insN) . ">";

                echo "<br><div class='button-section'><input type='submit' class='mod' name='Sign Up' value='Modifica' /></div>";
                echo "</form>";
          } else {
                    echo "<p>Nessun risultato presente nel database - <a href='...viewdbadmin.php'>aggiorna la pagina</a>.</p></div>";
                    echo "</form>";
                }

    mysqli_close($conn);
        echo "</div>";
?>

3rd part (PHP receive data and loop throw the array to insert it into the database)

<?php
        //da qui INSERT DATA
        if (!empty($_POST["prodN"])) {

            echo "<br>*************************** QUINDI prodN[] NON E' EMPTY **************************************<br>";
            // FAI UN LOOP TRA TUTTE LE RIGHE NEW

            $numR = $_POST['numN'];
            var_dump($numR);
            echo "<br>";
            //echo "<br>*************************** numR = $numR **************************************<br>";
            $dataR = $_POST['todayN'];
            var_dump($dataR);
            echo "<br>";
            //echo "<br>*************************** todayN = $dataR **************************************<br>";
            $prodR = $_POST['prodN'];
            var_dump($prodR);
            echo "<br>";
            //echo "<br>*************************** prodR = $prodR **************************************<br>";
            $varR = $_POST['varN'];
            var_dump($varR);
            echo "<br>";
            //echo "<br>*************************** varR = $varR **************************************<br>";
            $imgR = $_POST['imgN'];
            var_dump($imgR);
            echo "<br>";
            //echo "<br>*************************** imgR = $imgR **************************************<br>";
            $availableR = ($_POST['availableN']);
            var_dump($availableR);
            echo "<br>";
            echo "<br>*************************** availableR = $availableR **************************************<br>";
            for ($r=0; $r<count($prodR); $r++) {
            if ($numR[$r] != "" && $dataR[$r] != "" && $prodR[$r] != "" && $varR[$r] != "" && $imgR[$r] != "" && $availableR[$r] != "") {
                    //insert function
                    require_once('datainsert.php');
                    insertProds($conn, $numR[$r], $dataR[$r], $prodR[$r], $varR[$r], $imgR[$r], $availableR[$r]);
                    }
                }
//END
        }
?>

I'm totally sure it's not an elegant code the one I've written, but works great for the purpose I need, so pls be kind because I'm not a professional programmer and I'm doing this as a challenge for my parents.

Thanks in advance for your time and help.

UPDATE1

While I'm waiting an answer I've tried two possibile different solution.

The 1st was to simply move all the code at the bottom of the page (my thought were "maybe I'm a problem of position", but what guess what? It didn't make any difference.

The 2nd was to try another code involving jQuery and Ajax POST method and so I've used this code:

<script>
     $(document).ready(function(){
                var i = 1;
                $("#add-row").click(function(){
                        i++;

                        var dataNew = $("#dataNew").val();
                        var data = $("#data").val();
                        //var counter = $("#countN").val();
                        //alert("counter è:"+counter);
                        //counter++;

                        var markup = '<tr id="row' + i + '"><td class="count">' + i + '<input type="hidden" id="countN" name="numN[]" value=' + i + '></td><td class="data">' + dataNew + '<input type="hidden" id="data" name="todayN[]" value=' + data + '></td><td class="prod"><input type="text" id="prod" name="prodN[]" placeholder="Nuovo prodotto"></td><td class="var"><input type="text" id="var" name="varN[]" placeholder="Varietà"></td><td class="img"><input type="text" id="img" name="imgN[]" placeholder="Inserisci url della foto"></td><td class="available"><label class="choice" for="avaYnew"><input type="radio" id="avaYnew" name="availableN[]" value="yes" > Sì</label><label class="choice" for="avaNnew"><input type="radio" id="avaNnew" name="availableN[]" value="no" > No</label></td><td class="rows"><input type="button" name="delete-row" class="delete-row" id='+ i +' value="Rimuovi"></td></tr>';

                        alert(markup);
                        $("#addProds").append(markup);

                        //$("#countTotN").val(counter);
                        //var countTotN = $("#countTotN").val();
                        //$("#countN").val(counter);
         });

                $(document).on("click", ".delete-row", function() {
                    var button_id = $(this).attr("id");
                    altert(button_id);
                    $('#row' + button_id + '').remove();
                });

                $('#submit').click(function() {
                    $.ajax({
                        url:"viewdbadmin.php']",
                        method:"POST",
                        data:$('#items').serialize(),
                        success:function(data) {
                            alert(data);
                            $('#items')[0].reset();
                        }
                });
     });
    });
 </script>

As a result, PHP kept working great, but jQuery appended data kept on being excluded from arrays containing data sent to PHP. Infact I keep on receiving only the 1st data I insert in my form for new products (the one from the 1st row of the table) but any data from appended .

Thanks again, I hope someone will seems because I'm testing this part of code since a week but I'm not able to find a solution.

Sorry I've added an answer to ask how could I be more useful to receive your help. How can I? Thanks.

1 Answers1

0

SOLUTION

Dunno why, but it wasn't working because inside there was this row just before the table:

echo "<br>Prodotti presenti nel database (ultimo aggiornamento al " . date("d.m.Y", strtotime($rowTit[0]))."):</div>";

This part of table was used to show last date used for update. Moving this row outside solved the problem.

So the code now is (I hope it might help someone else):

      $sqlTit = "SELECT DATA FROM elencoprodotti WHERE DATA = (SELECT MAX(DATA) FROM elencoprodotti) ORDER BY DATA DESC LIMIT 1";
      $resultTit = $conn->query($sqlTit);

      if (!$resultTit) {
          echo 'Could not run query: ' . mysqli_error($conn);
          exit;
      }
            $rowTit = mysqli_fetch_row($resultTit);
            $lastUpd = date("d.m.Y", strtotime($rowTit[0]));

            echo "<div>";

            if (empty($lastUpd)) {
                echo "<br>Ultimo aggiornamento prodotti:<font color='red'> non disponibile</font></div>";
            } else {
                echo "<br>Prodotti presenti nel database (ultimo aggiornamento al " . $lastUpd ."):</div>";
            }


            echo "<form action=" . htmlspecialchars($_SERVER['PHP_SELF']) . " method='POST'>";

      //MOSTRA I RISULTATI
      $sqlMag = "SELECT * FROM elencoprodotti WHERE DATA = (SELECT MAX(DATA) FROM elencoprodotti) ORDER BY DATA DESC, PRODOTTO ASC";
      $resultMag = $conn->query($sqlMag);

      $count = 0;

      if (!empty($resultMag) && $resultMag->num_rows > 0) {

                echo "<table>";
  • 1
    It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman May 29 '20 at 16:46