0

Please help me. Thanks I have a form which contains function's javascript and in function's javascript contains html code.

My question is : how to send in database my form ?

This is my form :

    <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Créer une facture</title>
    <link rel="stylesheet" href="style.css" media="all" />
  </head>
  <body>

<form action="affiche.php" method="post">

<fieldset>
            <legend>Contenu de la facture formation</legend>
            <div id="ID_container">
            <textarea name="prestation[]" rows="4"
              placeholder="Prestation" required></textarea>
            <input type="number" placeholder="Nombre de jours" name="nbjours[]" required>
            <input type="number" placeholder="Tarif journalier" name="tarifjour[]" required>
            </div>
            <button onclick="ajout(this);">+ Ajouter une prestation</button>

            <br/><br/>
            <input type="submit"  name="envoyer" value="Envoyer"/>
            </fieldset>

</form> 
<script src="js/fonct.js"></script>
</body>
</html> 

This is function JS:

function ajout(element){
        var container = document.getElementById('ID_container');

        var str ='<span><textarea name="prestation[]" rows="4" type="text" placeholder="Prestation"></textarea>    </span><span><input name="nbjours[]" type="number" placeholder="Nombre de jour">    </span><span><input name="tarifjour[]" type="number" placeholder="Tarif journalier">    </span><span><input type="button" onclick="suppression(this)"; value="x"></span><br/>';        
        var divNewExp = document.createElement("div");
        divNewExp.innerHTML = str ;
        container.appendChild(divNewExp);

      }

function suppression(element){
        var container = document.getElementById('ID_container');
        container.removeChild(element.parentNode.parentNode);
      }

Here i want send these data in database and displays data, but it is not work, data are not send in database :

    <?php
require_once 'connexion.php';
// On vérifie si la variable existe et sinon elle vaut NULL
$prestation = isset($_POST['prestation']) ? $_POST['prestation'] : NULL;
$nbjours = isset($_POST['nbjours']) ? $_POST['nbjours'] : NULL;
$tarifjour = isset($_POST['tarifjour']) ? $_POST['tarifjour'] : NULL;

//On récupère les différentes valeurs  sous forme d'une chaine de caractères séparées par une virgule
$prestation=implode(",", $_POST['prestation']);
$nbjours=implode(",", $_POST['nbjours']);
$tarifjour=implode(",", $_POST['tarifjour']);

$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour)
    VALUES ("'.$prestation.'", "'.$nbjours.'", "'.$tarifjour.'")');
    $req->execute(array(  'prestation'=> $prestation,
                          'nbjours'=> $nbjours,
                          'tarifjour'=> $tarifjour));
      echo "les données ont bien étés insérées dans la base de données";
      $base = null;
?>

        <tr>
            <?= foreach((array)$req as $presta) ?>
            <td class="desc"><?php echo $presta['prestation'] ?></td>
            <td class="qty"><?php echo $presta['nbjours'] ?></td>
            <td class="unit"><?php echo $presta['tarifjour'] ?></td>
            <td class="total"><?php echo $presta['tarifjour'] * $presta['nbjours'] ?></td>
          </tr>
2
  • You're not using prepare the right way. I'd suggest you learn about the proper way to use prepared statements and binding with PDO Commented Mar 13, 2018 at 14:04
  • You should also add type="button" to your button in the form since the default behavior is "submit" (and will submit the form which I'm guessing you don't want). Commented Mar 13, 2018 at 14:08

1 Answer 1

2

You're trying to get data from INSERT request, and you're not using prepare/execute properly. It just can't work the way you made it. As aynber said, you should read PDO documentation

Here is some tips that can help you out :

1. Fix your prepare statement / execute

$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour) VALUES (:prestation, :nbjours, :tarifjour)');
$req->execute(array(
  ':prestation' => $prestation,
  ':nbjours'    => $nbjours,
  ':tarifjour'  => $tarifjour
));

I guess you need to add one row for each of your prestation, not saving every added prestation in one row, so you have to update your query to reflect that

// generate request params
$params = [];
$values = '';
foreach ($_POST['prestation'] as $key => $prestation) {
    $params[':prestation' . $key] = $prestation;
    $params[':nbjours' . $key]    = $_POST['nbjours'][$key];
    $params[':tarifjour' . $key]  = $_POST['tarifjour'][$key];

    $values .= '(:prestation' . $key . ', :nbjours' . $key . ', :tarifjour' . $key . '),';
}

// remove trailing ","
$values = rtrim($values, ',');
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour) VALUES ' . $values);
// insert every rows in DB
$req->execute($params);

2. Generate rows from posted data or fetch them from database

In this example, I'll only show you the first option

// prepare facturation data
$facturation[] = [
  'prestation' => $prestation,
  'nbjours'    => $_POST['nbjours'][$key],
  'tarifjour'  => $_POST['tarifjour'][$key],
];

<?php foreach ($facturation as $presta) : ?>
<tr>
    <td class="desc"><?= $presta['prestation'] ?></td>
    <td class="qty"><?= $presta['nbjours'] ?></td>
    <td class="unit"><?= $presta['tarifjour'] ?></td>
    <td class="total"><?= $presta['tarifjour'] * $presta['nbjours'] ?></td>
  </tr>
<?php endforeach; ?>

3. Fix your buttons to prevent submitting form when using + or x buttons

As Magnus Eriksson said, you need to add type="button" in your button elements.

In your index file, use

<button type="button" onclick="ajout(this);">+ Ajouter une prestation</button>

Instead of

<button onclick="ajout(this);">+ Ajouter une prestation</button>

In fonct.js, use

<button type="button" onclick="suppression(this)">x</button>

Instead of

<input type="button" onclick="suppression(this)"; value="x">

4. Check if every needed data exists before executing every other steps to prevent errors

Here's my full working affiche.php file (without variables check) :

<?php
require_once 'connexion.php';
// On vérifie si la variable existe et sinon elle vaut null
$prestation = isset($_POST['prestation']) ? $_POST['prestation'] : null;
$nbjours = isset($_POST['nbjours']) ? $_POST['nbjours'] : null;
$tarifjour = isset($_POST['tarifjour']) ? $_POST['tarifjour'] : null;

//On récupère les différentes valeurs  sous forme d'une chaine de caractères séparées par une virgule
$prestation=implode(",", $_POST['prestation']);
$nbjours=implode(",", $_POST['nbjours']);
$tarifjour=implode(",", $_POST['tarifjour']);

// generate request params
$params = [];
$values = '';
$facturation = [];
foreach ($_POST['prestation'] as $key => $prestation) {
    $params[':prestation' . $key] = $prestation;
    $params[':nbjours' . $key]    = $_POST['nbjours'][$key];
    $params[':tarifjour' . $key]  = $_POST['tarifjour'][$key];

    $values .= '(:prestation' . $key . ', :nbjours' . $key . ', :tarifjour' . $key . '),';

    // prepare facturation data
    $facturation[] = [
      'prestation' => $prestation,
      'nbjours'    => $_POST['nbjours'][$key],
      'tarifjour'  => $_POST['tarifjour'][$key],
    ];
}
// remove trailing ","
$values = rtrim($values, ',');
$req = $base->prepare('INSERT INTO facturation (prestation, nbjours, tarifjour) VALUES ' . $values);
$req->execute($params);
echo "les données ont bien étés insérées dans la base de données";
$base = null;
?>

<table>
  <thead>
    <tr>
      <th>Prestation</th>
      <th>Nb jours</th>
      <th>Tarif /jour</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($facturation as $presta) : ?>
    <tr>
        <td class="desc"><?= $presta['prestation'] ?></td>
        <td class="qty"><?= $presta['nbjours'] ?></td>
        <td class="unit"><?= $presta['tarifjour'] ?></td>
        <td class="total"><?= $presta['tarifjour'] * $presta['nbjours'] ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

I hope it helps !

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

13 Comments

Thank you very much, thank you, it makes me move forward. But I get confused that I have to add extra values ​​in the insert into query, for example, here is my entire query:
$req = $base->prepare('INSERT INTO facturation (num, client, prestation, nbjours, tarifjour, dateFacture, facturede, conditions) VALUES (:num, :client, :prestation, :nbjours, :tarifjour, :dateFacture, :facturede, :conditions)');
$req->execute(array( ':num' => $num, ':client' => $client, ':prestation'=> $prestation, ':nbjours'=> $nbjours, ':tarifjour'=> $tarifjour, ':dateFacture'=> $dateFacture, ':facturede'=> $facturede, ':conditions'=> $conditions));
You just have to add a line for each field you want, then update the line where $value is set to add every field
Example for the field dateFacture : add the line $params[':dateFacture' . $key] = $_POST['dateFacture'][$key]; and add , :dateFacture' . $key . ' to the line where I define $value in the foreach
|

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.