Morpheus
Morpheus

Reputation: 57

How do i create an array from form input

I'm trying to write a php script that takes the input from this form and creates an array with a unique key for each input box/text boxes content.

<div class="container">
  <div class="row">
    <div class="col-3 mx-auto">
      <form action="adminhandler.php">
        <div class="form-group">
          <label for="product name">Enter product name</label>
          <input type="text" class="form-control" id="productName" aria-describedby="emailHelp" placeholder="" name="productname">
        </div>
        <div class="form-group">
          <label for="product name">Select product category</label>
          <select name="select" class=" custom-select">
          <option selected>Open this select menu</option>
          <option value="1">Formal Shoes</option>
          <option value="2">Sneakers</option>
          <option value="3">Tracksuits</option>
          <option value="3">Clothing</option>
          <option value="3">Accessories</option>
        </select>
        </div>
        <div class="form-group">
          <label for="product price">Enter product price(Naira)</label>
          <input type="text" class="form-control" id="productPrice" aria-describedby="emailHelp" placeholder="" name="price">
        </div>
        <div class="form-group">
          <label for="product name">Select image</label>
          <input type="file" class="form-control-file" id="productimage" aria-describedby="emailHelp" placeholder="">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </div>
</div>

Upvotes: 0

Views: 1067

Answers (1)

Dhaval Chheda
Dhaval Chheda

Reputation: 924

I think you want to use a form as an array and then pass the same data as an array.If you are using the $_POST, you will need to use the name attribute of HTML. And use something like this :

<input name="person[1][first_name]" value="jane" />

This when passing through PHP will be sent as Array. Here is the reference : http://php.net/manual/en/reserved.variables.post.php An Excerpt from one of the contributors :

   <form>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />

<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>

When Trying To Process Values using PHP

<?php
var_dump($_POST['person']);
//will get you something like:
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>

Upvotes: 1

Related Questions