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

2

2 Answers 2

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.

1
  • hi, thanks for your response, but is not working, it gets empty to the database Commented Mar 6, 2014 at 17:35
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);
4
  • This doesn't trim the trailing comma and uses the wrong escape function. Commented Mar 6, 2014 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 Commented Mar 6, 2014 at 17:39
  • Thanks for pointing out the typo, Dan. :) However, there is no trailing comma. The implode function will handle that. Commented Mar 7, 2014 at 8:43
  • Sorry, garbanm. There should be basic parentheses around the firstname. Commented Mar 7, 2014 at 8:45

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.