0

Hi guys,

im working on a bit of code which for 2 days is sending me around in circles :/

what i want to do is split an array into variables, so i can dynamically create a text box.

i'm trying various methods but think im chasing my tail now.

        $input_array = array($forSplitProduct);
        print_r($input_array);
        echo '<br>';
        echo '<br>';

        list($a) = $input_array;
        //echo $a;
        for($i = 0; $i < count($a); $i++){
        //  print_r($a);
            $b = explode(",", $a);
        //  print_r($b);
                for($i = 0; $i < count($b); $i++){
                    print_r($b[$i]);    
                }
        }
        echo '<br>';
        echo '<br>';

        $b = explode(",", $a);
        print_r($b);

that code outputs:
Array ( [0] => 1 Tonne Sand,1 Tonne Chippings, )

1 Tonne Sand1 Tonne Chippings

Array ( [0] => 1 Tonne Sand [1] => 1 Tonne Chippings [2] => )

what i would like it to do is each item, in this case "1 tonne sand" "1 tonne chippings" to be its own textbox, so:
<input name="item" type="text" value="1 tonne sand" />
<input name="item" type="text" value="1 tonne chippings" />

any ideas?

many thanks
Ade

2
Contributors
5
Replies
33
Views
3 Years
Discussion Span
Last Post by cereal
1

So this should work, correct?

$forSplitProduct = 'productA,productB';
$values = explode(',', $forSplitProduct);

foreach($values as $value)
{
    echo "<input type='text' name='item[]' value='$value' />";
}

By setting item[] you get an array of results, otherwise you have to set unique names for each input field.

Edited by cereal

0

your code is brilliant mate, thank you,
but 2 problems, 1 the last textbox that renders is a blank textbox, im guessing this is because there is a , at the end of each item. secondly i cannot get th textboxes to post on the submit command, any ideas?

many thanks again :)

Edited by Sammys.Man: amended code

0

To avoid empty fields, empty spaces and repetitions you can change $values with:

$forSplitProduct = 'productA, productB , productA,';

$values = array_unique(array_map('trim', array_filter(explode(',', $forSplitProduct))));

array_filter will remove the empty value due to the extra comma, array_map is used to execute trim on each value of the array and remove spaces before and after each value, array_unique will remove duplicates, so that the above $forSplitProduct will return only two input fields and not four as in the previous code.

When you receive $_POST['item'] you have to loop it, because it will return an array:

Array
(
    [item] => Array
        (
            [0] => productA
            [1] => productB
        )

    [submit] => send
)

So:

if(is_array($_POST['item']))
{
    foreach($_POST['item'] as $item)
    {
        # execute code:
        echo $item;
    }
}

Test script:

<?php

    $forSplitProduct = 'productA, productB , productA ,';

    if($_POST)
    {
        echo "<pre>";
        print_r($_POST);
        echo "</pre>";
    }

    $values = array_unique(array_map('trim', array_filter(explode(',', $forSplitProduct))));
    $result = array();

    foreach($values as $value)
    {
        $result[] = "<input type='text' name='item[]' value='$value' />";
    }

?>

<form method="post" action="">
    <?php
        echo implode(PHP_EOL."\t", $result);
    ?>

    <input type="submit" name="submit" value="send" />
</form>
0

Thank you for that bit of code and the time you spent writting it, it's definatly a leap forward :)
final question on the

if($_POST)
        {
            echo "<pre>";
            print_r($_POST);
            echo "</pre>";
        }

that prints out everything i need

Array
(
    [name] => Ade Mitchell
    [date_time] => 2014-08-14 / 08:24:00
    [1_Tonne_Sand] => 1 Tonne Sand
    [1_Tonne_Chippings] => 1 Tonne Chippings
    [Door_Lintel] => Door Lintel
    [Window_Lintel] => Window Lintel
    [1] => 1 Tonne Sand
    [2] => 1 Tonne Chippings
    [4] => Door Lintel
    [5] => Window Lintel
    [8] => 
    [item] => Array
        (
            [0] => 1 Tonne Sand
            [1] => 1 Tonne Chippings
            [2] => Door Lintel
            [3] => Window Lintel
        )

    [submit] => Submit
)

in the post.php script its

     <?php
        if($_POST)
        {
            echo "<pre>";
            print_r($_POST);
            echo "</pre>";
        }

            if(isset($_POST['submit'])){
                echo $_POST['name'] . '<br>';
                echo $_POST['date_time'] . '<br>';
                echo $_POST['item'];    
            }
        ?>

how can i get the elements from the item array so i can post them into a database?

i.e

    [item] => Array
        (
            [0] => 1 Tonne Sand
            [1] => 1 Tonne Chippings
            [2] => Door Lintel
            [3] => Window Lintel
        )

many thanks

0

It depends a lot on how you want to save this input, four different columns in this specific order and in a single row, plus $_POST['name']?

If you're going to use prepared statements you can simply submit $_POST['item'] because it is already an array, for example:

    $data = array_merge(array($_POST['name']), $_POST['item']);
    $stmt = $db->prepare("INSERT INTO tablename (name, item1, item2, item3, item4) VALUES(?, ?, ?, ?, ?)");
    $stmt->execute($data);

Pay attention to this:

$data = array_merge(array($_POST['name']), $_POST['item']);

$_POST['name'] is a string, to merge it with the $_POST['item'] needs to be an array, so array($_POST['name']), the above will create:

Array
(
    [0] => Ade Mitchell
    [1] => productA
    [2] => productB
    [3] => productC
    [4] => productD
)

Which ideally cannot be altered. However a user could use an external script to add input fields to the form and add columns to the final array:

Array
(
    [0] => Ade Mitchell
    [1] => productA
    [2] => productB
    [3] => productC
    [4] => productD
    [5] => hello         <-- remotely added by client
)

This will create an error on the insert query that sounds like this:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens'

So what you can do here is to sanitize and limit the amount of input that can be submitted. You have multiple choices, filter_input_array is one of these:

if($_POST)
{
    # filter config
    $config['item'] = array(
            'filter' => FILTER_SANITIZE_STRING,
            'flags'  => FILTER_REQUIRE_ARRAY,
        );

    $config['name'] = array(
            'filter' => FILTER_SANITIZE_STRING
        );

    # sanitize
    $post = filter_input_array(INPUT_POST, $config);

    # prepare data for the insert:
    # pick only the first 4 inputs from this array by selecting $items[0]
    $items = array_chunk($post['item'], 4);

    # merge it with $post['name']
    # the order is important because the name will be in the first place
    $data = array_merge(array($post['name']), $items[0]);

    # save to database
    require '../connections/pdo.php';
    $stmt = $db->prepare("INSERT INTO tablename (name, item1, item2, item3, item4) VALUES(?, ?, ?, ?, ?)");
    $stmt->execute($data);
}

Documentation:

If you have doubts post your insert query and the full form.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.