Jump to content

send array[] from php to mysql


Go to solution Solved by unasemana,

Recommended Posts

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?


Link to comment
https://forums.phpfreaks.com/topic/286771-send-array-from-php-to-mysql/
Share on other sites

First you need to sanitized/validate your input before attempting to place it in your db.

To extract the array values from your POST array:

 

$values = '';
foreach($_POST['firstname'] as $nm)
{
   if ($values == '')
       $values .= "VALUE ('$nm')";
   else
        $values .= ",('$nm')";
}

 

Then modify your query statement to use $values in place of your existing values, etc. 

Edited by ginerjm

No need to loop through the array. Here's an easier solution - but I added a lot of validation logic as well:

//Run array_map() with trim to trim all the values
//Use array_filter() to remove empty values
$firstnames = array_filter(array_map('trim', $_POST['firstname']));
 
if(!count($firstnames))
{
    echo "No data to insert";
}
else
{
    //Connect to DB
    $con=mysqli_connect("localhost","inputmultiplicad","inputmultiplicado","inputmultiplicado");
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    //Use array_map() with mysql_real_escape_string() to sanitize values
    $firstnamesSQL = array_map('mysql_real_escape_string', $firstnames);
    //Implode the values into a string for the query
    $values = "('" . implode("'), ('", $firstnames) . "')";
    $sql = "INSERT INTO input_field (firstname) VALUES {$values}";
    if (!mysqli_query($con, $sql))
    {
        die('Error: ' . mysqli_error($con));
    }
    //Output success message
    echo count($firstnames) . " record(s) added";
    //Close DB connection
    mysqli_close($con);
?>

EDIT: I just noticed you are using mysqli - so you can't use mysql_real_escape_string and I don't think there is a comparable function for mysqli. You should instead use a prepared statement and insert each record individually. Prepared statements will alleviate a lot of the overhead with running queries in loops. Although, if you would be running hundreds of record at once even that needs to be considered.

Edited by Psycho

EDIT: I just noticed you are using mysqli - so you can't use mysql_real_escape_string and I don't think there is a comparable function for mysqli. You should instead use a prepared statement and insert each record individually. Prepared statements will alleviate a lot of the overhead with running queries in loops. Although, if you would be running hundreds of record at once even that needs to be considered.

 

mysqli_real_escape_string

  • Solution

hi, thanks for your response,

 

I made it: this is working.

 

 

Why do you dont like serialize sKunBad?

 

What do you mean by : "prepared statement and insert each record individually" ? Pyscho

 

thanks for your asnwers

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


  
  


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




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


mysqli_close($con);
?>

@quickoldcar,

 

Thanks for the heads up ont he mysqli version of real_escape_string. I've been using PDO and when I did a search on php.net for "mysqli_real" it didn't find that function (but it does if I use "mysqli real" - no underscore).

 

 

 

What do you mean by : "prepared statement and insert each record individually" ? Pyscho

 

Prepared statements is a different way of constructing and executing queries which adds a lot of benefits. For example, when using a prepared statement properly you do not need to escape the data to prevent SQL Injection. Plus, if you use a 'prepared' query it can be reused without much of the overhead in running the query the first time. The database does some processing of a query before it is run. With a prepared statement it does that operation once and you can pass different variable to run the query again without the same overhead. I'll admit I don't really understand all of the details - and don't care to. But, prepared statements is definitely the right way to go. But, it will take some relearning and is not something anyone could cover in a forum post. You can do a search for some tutorials or guides. Then if you run into problems post back here.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.