0

I have a php website that makes a table using data fetched from a database. In the table I have a input so that the user can select how many of each item they want to buy. I have successfully made the ids of each input different by concatenating the ids.

Here is the php that makes the table:

<?php

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      echo "<tr>";
      echo "<td>" . $row['id'] . "</td>";
      echo "<td>" . $row['Article'] . "</td>";
      echo "<td>" . $row['Prix'] . "</td>";
      echo "<td>" . $row['PrixRetour'] . "</td>";
      echo "<td>" . $row['QuantiteeMaximale'] . "</td>";
      echo "<td>" . $row['Projet'] . "</td>";
      echo "<td id=\"quantity" . $row['id'] . "\"><input type=\"number\" name=\"quantity\" id=\"quantity\"></td>";
      echo "</tr>";
    }
} else {
    echo "0 results";
}
$conn->close();

?>

I need to write the total amount at the end of my table, but i don't know how to make a for loop in javascript so that the number in the input field is multiplied by the price. Is there an easy part of code that i could use to calculate the grand total price?

1 Answer 1

3

You don't need to do this in Javascript. You could just do it in your PHP code:

<?php

if ($result->num_rows > 0) {
    $grandTotal = 0;
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $grandTotal += $row['Prix'] * $row['QuantiteeMaximale'];

      echo "<tr>";
      echo "<td>" . $row['id'] . "</td>";
      echo "<td>" . $row['Article'] . "</td>";
      echo "<td>" . $row['Prix'] . "</td>";
      echo "<td>" . $row['PrixRetour'] . "</td>";
      echo "<td>" . $row['QuantiteeMaximale'] . "</td>";
      echo "<td>" . $row['Projet'] . "</td>";
      echo "<td id=\"quantity" . $row['id'] . "\"><input type=\"number\" name=\"quantity\" id=\"quantity\"></td>";
      echo "</tr>";
    }

    echo "Grand Total: {$grandTotal}"; // you might want to end your table before this. I'll leave formatting up to you.
} else {
    echo "0 results";
}
$conn->close();

?>

Also, here's a cleaner way to output your HTML:

<?php

if ($result->num_rows > 0) {
    $grandTotal = 0;
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $grandTotal += $row['Prix'] * $row['QuantiteeMaximale'];

      ?>

      <tr>
          <td><?= htmlentities($row['id']); ?></td>
          <td><?= htmlentities($row['Article']); ?></td>
          <td><?= htmlentities($row['Prix']); ?></td>
          <td><?= htmlentities($row['PrixRetour']); ?></td>
          <td><?= htmlentities($row['QuantiteeMaximale']); ?></td>
          <td><?= htmlentities($row['Projet']); ?></td>";
          <td id="quantity<?= $row['id']; ?>"><input type="number" name="quantity"></td>
      </tr>

      <?php
    }

    echo "Grand Total: {$grandTotal}"; // you might want to end your table before this. I'll leave formatting up to you.
} else {
    echo "0 results";
}
$conn->close();

?>

If you want to use the quantity field in the table itself, you could do something like this. It's a pretty quick solution. You'd probably want to refine it. But it's at least something to work with.

<?php

if ($result->num_rows > 0) {

    echo "<table id='items'>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $grandTotal += $row['Prix'] * $row['QuantiteeMaximale'];

      ?>

      <tr>
          <td><?= htmlentities($row['id']); ?></td>
          <td><?= htmlentities($row['Article']); ?></td>
          <td><?= htmlentities($row['Prix']); ?></td>
          <td><?= htmlentities($row['PrixRetour']); ?></td>
          <td><?= htmlentities($row['QuantiteeMaximale']); ?></td>
          <td><?= htmlentities($row['Projet']); ?></td>";
          <td><input data-price='<?= floatval($row['Prix']); ?>' data-max-quantity='<?= intval($row['QuantiteeMaximale']); ?>' type="number" name="quantity"></td>
      </tr>

      <?php
    }

    ?>

    </table>

    <p>Grand Total: $<span id='grandTotal'></span></p>

    <script>
        (() => {
            const updateGrandTotal = (grandTotalEl, inputEls) => {
                grandTotalEl.innerText = inputEls.reduce((total, inputEl) => {
                    const maxQuantity = parseInt(inputEl.dataset.maxQuantity)

                    if(parseInt(inputEl.value) > maxQuantity) inputEl.value = maxQuantity
                    if(parseInt(inputEl.value) < 0) inputEl.value = 0

                    const price = parseFloat(inputEl.dataset.price)
                    const quantity = parseInt(inputEl.value)

                    if(isNaN(quantity)) return total

                    return total + (price * quantity)
                }, 0)
            }

            const tableEl = document.getElementById('items')
            const grandTotalEl = document.getElementById('grandTotal')
            const quantityInputEls = tableEl.querySelectorAll('input[name=quantity]')

            quantityInputEls.forEach(el => el.addEventListener('keyup', () => updateGrandTotal(grandTotalEl, inputEls)))
        })()
    </script>

    <?php
} else {
    echo "0 results";
}
$conn->close();

?>
Sign up to request clarification or add additional context in comments.

5 Comments

Well I think this would work perfectly, but I actually have to multiply the price by the number given in the input field at the end of the table. I need javascript so that i don't have to reload the page.
@Louis Ah, I see. You should edit your question and clarify that you want to multiple the price by the value in the quantity input field.
@Louis I updated the answer to calculate the grand total using the quantity field.
Now that i have tried the code it doesn't work. I don't have any errors in the console but the price doesn't show in the span of the grand total. Do you have any ideas why?
@Louis I just wrote it as an example. You'll probably have to debug and refine it. Try using the Chrome Dev Tools, or add some console.log statements to see what's going on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.