1

I have the following form in php, but I want to make the insert.php action, to insert everything in a new row in MySQL... I don't know how to do it, because there are several fieldsets, it's easy with one simple form, but not for each $_cliente and $_servicio

CODE UPDATE

<?php
require("database.class.php");
//database server
define('DB_SERVER', "localhost");

//database usuario
define('DB_USER', "root");
//database password
define('DB_PASS', "root");
define('DB_DATABASE', "nivelservicio");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$db->connect();
    $sql    = "SELECT * FROM servicios";
    $_row = $db->query($sql);
    $_servicios = array();
    while($row = $db->fetch_array($_row)) {
        $_servicios[$row['id']] = $row['nombre'];
    }

    $sql    = "SELECT * FROM clientes";
    $_row = $db->query($sql);
    $_clientes = array();
    while($row = $db->fetch_array($_row)) {
        $_clientes[$row['id']] = $row['nombre'];
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <style>
            body{
                margin:0;
                border:0;
            }
            #formfieldset{
                width: 350px;
                font-family: helvetica, sans-serif, verdana;
                font-size:12px;
            }

            h1 {
                font-size:36px;
                font-family: Georgia;
                font-style: italic;
                border-bottom:1px solid #000;
            }

            h2 {
                font-size:18px;
                font-color:#1E1E1E;
            }


        </style>
    </head>
    <body>
        <form action="insert.php" method="post">
        <div id="formfieldset">
            <?php foreach ($_clientes as $key_cliente => $cliente) :
                switch ($cliente) {
                    case "Produban":
                        $_servicios = array_diff($_servicios, array(
                            "GESTI",
                            "VULCANO"
                        ));
                        break;
                } ?>

                <h1><?php echo $cliente ?></h1>
                <input type='hidden' name='cliente_id[<?php echo $key_cliente ?>' value='<?php echo $key_cliente ?>'>
                <?php foreach($_servicios as $key_servicio => $servicio) : ?>
                    <h2><?php echo $servicio ?></h2>
                    <input type="hidden" name="servicio_id[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>]" value="<?php echo $key_servicio; ?>">
                    <label>Estado</label>
                    <select name="estado[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>">
                        <option value="OK">OK</option>
                        <option value="KO">KO</option>
                    </select>
                    <label>Texto</label><input type="text" name="texto">
                <?php endforeach; ?>
            <?php endforeach; ?>

            <br>
            <input type="submit" name="insertar" value="Insertar">
        </div>
        </form>
    </body>
</html>
<?php 
$db->close();
?>

insert.php

if(isset($_POST['insertar'])){
    var_dump($_POST);

    foreach ($clientes as $key_cliente => $cliente) {
        foreach ($servicios as $key_servicio => $servicio) {
            //echo $_POST['estado'][$key_cliente][$key_servicio] . '<br />';
            $sql = "INSERT INTO datos
                (servicio_id, cliente_id, estado, texto, fecha)
                VALUES
                ('".$_POST['servicio_id'][$key_cliente][$key_servicio]."',
                    '".$_POST['cliente_id'][$key_cliente][$key_servicio]."',
                        '".$_POST['estado'][$key_cliente][$key_servicio]."',
                            '".$_POST['texto'][$key_cliente][$key_servicio]."',
                                '".date('d-m-Y')."'
            )";

            $db->query($sql);
        }
    }
    echo "Valores insertados"; 
}

1 Answer 1

3

You need to change the name of your input fields to arrays like this:

<select name="estado[]">

And then in your PHP you can do this:

<?php

foreach ($_POST['estatdo'] as $key => $val) {
    echo $_POST['estatdo'][$key] . ' - ' echo $_POST['texto'][$key] . ' - ' echo $_POST['servicio_id'][$key] . '<br />'; 
}

Here's a full example:

<form action="insert.php" method="post">
<div id="formfieldset">
    <?php foreach ($_clientes as $key_cliente => $cliente) :
        switch ($cliente) {
            case "Produban":
                $_servicios = array_diff($_servicios, array(
                    "GESTI",
                    "VULCANO"
                ));
                break;
        } ?>

        <h1><?php echo $cliente ?></h1>
        <input type='hidden' name='cliente_id[<?php echo $key_cliente ?>]' value='<?php echo $key_cliente ?>'>
        <?php foreach($_servicios as $key_servicio => $servicio) : ?>
            <h2><?php echo $servicio ?></h2>
            <input type="hidden" name="servicio_id[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>]" value="<?php echo $key_servicio; ?>">
            <label>Estado</label>
            <select name="estado[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>]">
                <option value="OK">OK</option>
                <option value="KO">KO</option>
            </select>
            <label>Texto</label><input type="text" name="texto">
        <?php endforeach; ?>
    <?php endforeach; ?>

    <br>
    <input type="submit" name="insertar" value="Insertar">
</div>
</form>

So in this example we have a double nested array so instead of estado[] we have estado[][]. Also instead of using [] which makes an array with consecutive numeric keys (i.e., 0, 1, 2, 3) I've changed it to use the client id and the service id like this:

<select name="estado[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>]>

And then in your php you can loop through it like this:

foreach ($clientes as $key_cliente => $cliente) {
    foreach ($servicios as $key_servicio => $servicio) {
        echo $_POST['estado'][$key_cliente][$key_servicio] . '<br />;
    }
}
Sign up to request clarification or add additional context in comments.

11 Comments

This works fine, but there's a problem with $keys. I have 7 $_cliente and about 40 $_servicio... so it mess up with $key for cliente when > 7... ( ! ) Notice: Undefined offset: 8 in /var/www/nivelservicio/insert.php on line 14
Can you give me some advice please? Thank you :)
So i've updated the answer to show you how to do a nested array
@user1381537 My guess is that $_POST['insertar'] is not set. Try having var_dump($_POST) the very first line right after the opening <?php
Instead of having the submit button with the name have a hidden field with it instead <input type="hidden" name="insertar" value="true" /> The reason is you can submit forms without clicking the submit button. If you submit a form (i.e., by pressing enter from inside an input field) the submit button's value is NOT sent!
|

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.