0

im working on a project but first i would to understand one thing.

i have 2 input type text field with name="firstname[]" as an array (in the example im working with no jquery but it will be generated dinamically with it) and cant make it to mysql.

here is what i have: index.php

<html>
<body>

<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname[]"> <br>
Firstname 2: <input type="text" name="firstname[]">
<input type="submit">
</form>

</body>
</html>

insert.php

<?php
$con=mysqli_connect("localhost","inputmultiplicad","inputmultiplicado","inputmultiplicado");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }




$sql="INSERT INTO input_field (firstname)
VALUES
('$_POST[firstname]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

mysqli_close($con);
?>

the question is: how can i send the firstname[] array to the mysql database?

thanks for your time

garbanm
  • 31
  • 8
  • You should use `foreach` . Follow this example: http://stackoverflow.com/questions/779986/insert-multiple-rows-via-a-php-array-into-mysql – AdiCrainic Mar 06 '14 at 17:19
  • First, read this about SQL injections: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php - second, you would need to loop through the array. – WWW Mar 06 '14 at 17:19

2 Answers2

0

The following should generate the SQL statement you need. Remember to use mysql_escape_string before putting it into your database, though! Or even better, use PDO and bind the values. :)

$values = array();
$sql = "INSERT INTO table (firstname) VALUES ";
foreach ($_POST['firstname'] as $name) {
    $values[] = "('".mysql_real_escape_string($name)."')";
}
$sql .= implode(",", $values);
Philip Bennison
  • 519
  • 2
  • 10
  • This doesn't trim the trailing comma and uses the wrong escape function. – Dan Bechard Mar 06 '14 at 17:25
  • i get this error Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{firstname} VALUES ('Name 1'),('Name 2')' at line 1, im working with MAMP 2 – garbanm Mar 06 '14 at 17:39
  • Thanks for pointing out the typo, Dan. :) However, there is no trailing comma. The implode function will handle that. – Philip Bennison Mar 07 '14 at 08:43
  • Sorry, garbanm. There should be basic parentheses around the firstname. – Philip Bennison Mar 07 '14 at 08:45
0

This should work:

//Escape user input
$names = array_map('mysql_real_escape_string', $_POST[firstname]);

//Convert array to comma-delimited list
$names = rtrim(implode(',', $names), ',');

//Build query
$sql="INSERT INTO input_field (firstname) VALUES ('$names')";

Note: In general, it's better to use parameterized queries than mysql_real_escape_string(), but the latter is much safer than no escaping at all.

Dan Bechard
  • 5,104
  • 3
  • 34
  • 51