Robert W. Hunter
Robert W. Hunter

Reputation: 3003

PHP Form submit with arrays as rows

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"; 
}

Upvotes: 1

Views: 1258

Answers (1)

chrislondon
chrislondon

Reputation: 12031

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 />;
    }
}

Upvotes: 3

Related Questions