0

I am trying to insert values from a form into my mysql database. I have single value forms + array values from the form. How can I insert the array values into my database with the single form values attached to all rows?

The HTML:

Start:<br>
    <input type="text" name="start" id="start">

End:<br>
    <input type="text" name="end" id="end">

<input type="text" name="item[]" placeholder="Manufacturer #" /><br>

    <input type="text" name="description[]" placeholder="Description" /><br>

    <input type="text" name="item[]" placeholder="Manufacturer #" /><br>

    <input type="text" name="description[]" placeholder="Description" /><br>

    <input type="text" name="item[]" placeholder="Manufacturer #" /><br>

    <input type="text" name="description[]" placeholder="Description" /><br>

The PHP:

if (isset($_POST['submit']))
            {
                $link = mysql_connect('localhost',     'user', 'pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb") or die(mysql_error());
echo 'Connected successfully';

$query = "INSERT INTO agreement (start, end, item_number, item_description) VALUES ";
foreach($_POST['item'] as $i => $item) 
{ 
  // Get values from post.
  $item = mysql_real_escape_string($item);
  $description = mysql_real_escape_string($_POST['description'][$i]);
  $start = mysql_real_escape_string($_POST['start'][$i]);
  $end = mysql_real_escape_string($_POST['end'][$i]);

  // Add to database
  $query = $query." ('$start','$end','$item','$description') ,";
}
$query = substr($query,0,-1); //remove last char
$result = mysql_query($query);
            }

I will be changing the code to mysqli/pdo, I know that the current code is unsecure.

Any help is appreciated, thanks!

1 Answer 1

2

Just use $_POST['start'] and $_POST['end'] without array access since they will be the same each time. You can use array access for item and description.

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

2 Comments

Okay, it worked. For whatever reason it hadn't worked earlier...must have been an error in my prevous code. Thank you!
@hek2mgl instead of $_POST['start'][$i] just use $_POST['start']

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.