Jump to content

I'm passing data from a form to php to mysql the hard way--help me learn arrays


gamergomer

Recommended Posts

I'm simplifying this a lot:

 

First, I have a html form that asks for an answer 5 times to fill a column of data for my database. Really there are more than one question, but I'm going to simplify it here:

 

Color: <input type="text" size="15" maxlength="10" name="1color"></br>

Color: <input type="text" size="15" maxlength="10" name="2color"></br>

Color: <input type="text" size="15" maxlength="10" name="3color"></br>

Color: <input type="text" size="15" maxlength="10" name="4color"></br>

Color: <input type="text" size="15" maxlength="10" name="5color"></br>

 

Then my php file will have this at the beginning:

$1color=$_POST['1color'];

$2color=$_POST['2color'];

$3color=$_POST['3color'];

$4color=$_POST['4color'];

$5color=$_POST['5color'];

 

Then a little later, I'd have something like this:

INSERT INTO `mytable` ('id','colors')

VALUES (NULL, $1color),

VALUES (NULL, $2color),

VALUES (NULL, $3color),

VALUES (NULL, $4color),

VALUES (NULL, $5color);

 

Now that's all fine and dandy for a single item, but when you have 10 items and a longer table, it makes it more complicated and harder to change things later. So I want to change the individual color1, color2, etc into an array and then have it put the arrays into the table. Can I put stuff into an array from the form? Or how do I do it at the begging of the php file? And then how do handle the data input?

 

If anyone can help or point me in the right direction, I'd appreciate it.

If you name your form elements color[] you will end up with an array within $_POST['color']. You can then easily loop through this array and do your inserts.

 

This is will be something like  that :

<form method="POST" action="index.php" >
  1: <input type="checkbox" name="cid[]" value="1">
  2: <input type="checkbox" name="cid[]" value="2">
  3: <input type="checkbox" name="cid[]" value="3">
  4: <input type="checkbox" name="cid[]" value="4">
  5: <input type="checkbox" name="cid[]" value="5">
  6: <input type="checkbox" name="cid[]" value="6">
  <input type="submit" name="GO">
</form>

<?php
if($_POST["GO"]) {
    $cid = $_POST["cid"];
  	foreach ( $cid as $id ) {
  echo "<br>".$id;
        }
}
?>

 

The SQL query can be generated on this way :

$checkedColors = "('".implode("'),('", $cid)."')";

$sql = "INSERT INTO `mytable` (colors) VALUES $checkedColors";

 

[attachment deleted by admin]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.