0

I have this code here:

<?php while($rowequipment = mysql_fetch_assoc($sqlequipment)) {
echo '<input type="checkbox" name="equipment[]" value="'.$rowequipment['equipmentid'].'"/>    <input type="text" name="count[]" id="count[]" size="3" value=""/>'
.$rowequipment['description']."<br />";
}?>

This creates a list of checkboxes to select which equipment the user wants and text boxes to put in the number required.

Is it possible to somehow store the data in an associative array in php so that i cant then transfer this into a database? for example:

equipmentid    count
1              2
3              1

Or is there a different way to do this.

Thanks.

2
  • Firstly, never assign static element ID's in a loop. Multiple HTML elements with the same id="" is never valid. Secondly, what exactly do you mean? Do you mean you want to put the data in the database after the form you are generating has been submitted? Or something else? Commented Nov 25, 2011 at 10:35
  • @DaveRandom Yeah, i would like to submit the database into the database after the form has been submitted Commented Nov 25, 2011 at 10:40

2 Answers 2

2

You can do:

<form method="post">
<?php
$row[0]['equipmentid'] = 1;
$row[0]['description'] = "test1";
$row[1]['equipmentid'] = 2;
$row[1]['description'] = "test2";

foreach($row as $rowequipment)
{
    $e_id = $rowequipment['equipmentid'];
    echo '<input type="checkbox" name="equipment['.$e_id.'][id]" value="'.$e_id.'"/> ';
    echo '<input type="text" name="equipment['.$e_id.'][count]" id="count'.$e_id.'" size="3" value=""/> ';
    echo rowequipment['description']."<br />";
}
?>
<input type="submit" value="aa"/>
</form>

and the result will be:

array(1) {
  ["equipment"]=>
  array(2) {
    [1]=>
    array(2) {
      ["id"]=>
      string(1) "1"
      ["count"]=>
      string(1) "4"
    }
    [2]=>
    array(2) {
      ["id"]=>
      string(1) "2"
      ["count"]=>
      string(1) "6"
    }
  }
}

now change the foreach with your while and you will have the same result.

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

Comments

0

PHP will parse form values that use the square brackets and it will also work using IDs so assuming you don't actually need both checkboxes you can have:

echo '<input type="text" name="count['.$rowequipment['equipmentid'].']" ';
echo 'id="count['.$rowequipment['equipmentid'].']" size="3" value=""/>';
echo $rowequipment['description']."<br />";

Note there are no quotes around the id within the square brackets in the HTML.

Comments

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.