1

I am trying to save an array to $_POST['fetched_devices_array'] = array() and when I try to echo it inside the HTML form it prints the elements of it but when I try to send it to PHP after submission it is empty-I tried printing it after submission when I was receiving it in PHP.

Here is the code where I am setting it:

 <tbody>
        <form action="" method="POST">
            <?php
            echo "<table>
                <tr>
                <th>Customer ID</th>
                <th>Report ID</th>
                <th>Report message</th>
                <th>Device</th>
                <th>Device no.</th>
                <th>Barcode</th>
                <th>IMEI</th>
                <th>Sale-date</th>
                </tr>";
            $_POST['fetched_devices_array'] = array();
            //$_SESSION['countable_array'] = [];
            while ($row2 = $clientUsername->fetch_assoc()) {

                $_SESSION['cl_username'] = $row2["username"];
                while ($row = $message->fetch_assoc()) {

                    $_SESSION['accept'] = $row["acceptance"];
                    $_SESSION['client_comment'] = $row["message"];
                    $_SESSION['name'] = $row["name"];
                    $_SESSION['sales_date'] = $row["sales_date"];
                    $_SESSION['date_sent'] = $row["date_sent"];

                    $arr = $row['device_id'];
                    array_push($_POST['fetched_devices_array'], $arr);
                    ?>

            <?php if ($row['acceptance'] == 3) {
                        if ($message->num_rows > 1) {
                            echo "<tr> <td>
                              " . '<input type=checkbox name=devices[] value=' . $row['dev_id'] . '>' . "
                        </td> <td>" . $cus_id . " </td> <td>" . $rep_id . "</td> <td>" . $_SESSION['client_comment'] . "</td> <td>" . $_SESSION['name'] . "</td> <td>" . $row["device_no"] . "</td> <td>" . $row["barcode"] . "</td> <td>" . $row["serial_imei"] . "</td> <td>" . $row["serial_no"] . "</td> <td>" . $row["sales_date"] . "</td></tr>";
                            echo "</table>";
                        } else {
                            echo "<tr>
               <td>" . $cus_id . " </td> <td>" . $rep_id . "</td> <td>" . $_SESSION['client_comment'] . "</td> <td>" . $_SESSION['name'] . "</td> <td>" . $row["device_no"] . "</td> <td>" . $row["barcode"] . "</td> <td>" . $row["serial_imei"] . "</td> <td>" . $row["serial_no"] . "</td> <td>" . $row["sales_date"] . "</td></tr>";
                            echo "</table>";
                        }
                    } else {
                        echo "<tr>
           <td>" . $cus_id . " </td> <td>" . $rep_id . "</td> <td>" . $_SESSION['client_comment'] . "</td> <td>" . $_SESSION['name'] . "</td> <td>" . $row["device_no"] . "</td> <td>" . $row["barcode"] . "</td> <td>" . $row["serial_imei"] . "</td> <td>" . $row["serial_no"] . "</td> <td>" . $row["sales_date"] . "</td></tr>";
                        echo "</table>";
                    }
                }
            }

            ?>


            <?php while ($row3 = $acceptance->fetch_assoc()) {
                if ($row3['acceptance'] == '3') { ?>

                    <div class="input-group">
                        <label>If reject, please write the reason below:</label>
                        <textarea name="admin_comment" rows="7" cols="27"><?php echo $admin_comment; ?></textarea>
                    </div>

                    <p>
                        Return device to :
                        <?php
                                $sql = "SELECT id, username, user_type FROM users";
                                $result = $db->query($sql);

                                echo "<select name='device_manufacturer'>";
                                $nothing = "Nothing selected";
                                echo "<option value='" . $nothing . "'>" . $nothing . "</option>";
                                while ($row = $result->fetch_assoc()) {
                                    if ($row['user_type'] === 'manufacturer' || $row['user_type'] === 'admin') {
                                        echo "<option value='" . $row['id'] . "'>" . $row['username'] . "</option>";
                                    }
                                }
                                echo "</select>";
                                ?>
                    </p>

                    <input type="submit" name="rejected" value="Reject report" />
                    <input type="submit" name="accepted" value="Accept report" />
        </form>
    </tbody>

Here I am receiving:

$fetched_devs = $_POST['fetched_devices_array'];

1 Answers1

0

You should not manually populate the $_POST array. It will automatically be populated if your form is set up correctly.

As an example, create an <input> of type text and give it the name of fetched_devices_array[]. Notice the double-square brackets. This will ensure that your PHP script will receive an array of device IDs.

...
while ($row = $message->fetch_assoc()) {
   ...

   <input type="text" name="fetched_devices_array[]" value="<?php echo $row['device_id']; ?>">
}

...
<input type="submit" name="rejected" value="Reject report">
<input type="submit" name="accepted" value="Accept report">

Now, when you submit your form your post array will have an element named _fetched_devices_array_ and it will be an array of items which you can process.

EDIT

as you can see, I have embeded PHP into HTML which is not safe I guess.

There is nothing insecure about embedding PHP in HTML. The reason people avoid it is because it can easily lead to spaghetti code.

Since I have embeded PHP in HTML I need to save those values that i fetching from DB somewhere so that I can use them later, thats the reason why I am using a lot of $_SESSION but I am gonna try to switch most of them to $_POST but there is one problem, there are some values that I need before submiting a form, so where else can I save values which I need when I am not submitting forms?

Not sure what you're doing with the DB data let me try to explain it with some pseudo-code. The important thing to understand is that you can retrieve the data you need from the DB at any time. You don't need to include it in the session or the form unless you want the user to interact with it.

// Form processing
if ($form->wasSubmitted) {
    $selectedDeviceIds = $form->getSelectedDeviceIds()
    $selectedUserIds = $form->getSelectedUserIds()

    // Now, if you need to query your DB to get other information, do it here.
    $dbData = SELECT date_sent, sales_date, ... FROM table;

    // Do stuff with `$selectedDeviceIds`, `selectedUserIds ` and `$dbData`
}

// Get the data that you need for your form.
// This should only be the data that your user needs to interact with.
// For example, show them a list of device IDs which they need to choose.
$availableDeviceIds = SELECT id FROM devices;

$users = SELECT username FROM users;

<form>
    <select>
        foreach ($availableDeviceIds as $deviceId)
            <option value="$deviceId">
        endforeach
    </select> **Choose the device IDs you want to buy

    <select>
        foreach ($users as $user)
            <option value="$user">
        endforeach
    </select> **Choose the users you want to delete

    <submitButton>
</form>
waterloomatt
  • 3,662
  • 1
  • 19
  • 25
  • +1 for the answer. Is there a better way to populate an array and pass it to the php code where I want to? I could also use $_SESSION[] but I dont think its safe to use them. So, besides $_post is there another way I could do this? –  Nov 23 '19 at 12:39
  • You have a few options but if you're using HTML forms to send the data, they all fundamentally are either _get_ or _post_ requests. Sessions are effectively 100% safe to use and are the backbone of any web application that needs to maintain state. But, it's important to realize that session data is _set_ and _read_ on the _server-side_. They cannot pass data from the client to the server. You can think of sessions as rudimentary databases. – waterloomatt Nov 23 '19 at 18:04
  • oh, what can I do in this case, I am using $_SESSION[] way to many times, so should I switch to $_POST and $_GET to pass data? I am working on localhost so thats why I didnt really think about that problem before. –  Nov 25 '19 at 12:52
  • Why are you using session in this case? Looks like you're reading data from your database and then setting it in the session. Maybe if you edit your question and show your processing logic, we can help guide you. – waterloomatt Nov 25 '19 at 13:20
  • as you can see, I have embeded PHP into HTML which is not safe I guess. Since I have embeded PHP in HTML I need to save those values that i fetching from DB somewhere so that I can use them later, thats the reason why I am using a lot of $_SESSION but I am gonna try to switch most of them to $_POST but there is one problem, there are some values that I need before submiting a form, so where else can I save values which I need when I am not submitting forms? –  Nov 27 '19 at 19:40
  • Thanks a lot for your answer, however, I have heard so many times that embedding PHP into HTML makes the code prone to SQL injections as that way you are showing the queries in the client side, is that true? –  Nov 27 '19 at 20:03
  • 1
    _embedding PHP into HTML makes the code prone to SQL injections_. No, not that is not correct. SQL injection attacks are possible when you embed user input directly into your queries. https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – waterloomatt Nov 27 '19 at 20:29
  • 1
    Again, it is important to understand the difference between client-side and server-side programming. **Everything** between the PHP tags (``) is executed on the server. When you mix HTML and PHP, you aren't really mixing them in terms of execution because your server executes the PHP and sends back and HTML response. But you are mixing them in terms of source code, which can lead to an ugly mess that is difficult to maintain. Hope that makes sense. – waterloomatt Nov 27 '19 at 20:35