简体   繁体   中英

MySQL insert - Values coming from inputs using name array. (PHP)

I am currently producing a form via mysql / php. I have well over 1500 inputs with unique values and I would like to insert them into a mysql table (1 value / row)

I am creating the form this way:

echo "<input type='text' name='combination[]' value='justsometext". $row['name'] ."'><br />";

I have around 1500 inputs like this and I would like to insert them into one column, how do I go about?

I am using the following code to insert, but it is only inserting 0s instead of the actual values:

foreach ($_POST['combination'] as $combination) {
$sql="INSERT INTO alphabet_combination (combination)
VALUES
('$combination')";
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}

First of all: How can I prevent SQL injection in PHP?

Second: 1500 inputs? Wow... You have to double check if your php.ini configuration will handle it.

If you really want to put 1500 values in one column - maybe you should consider to serialize array and keep it that way?

In prepared statement this will look like this:

$combinations = serialize($_POST['combination']);

$q = mysqli_prepare($con, 'INSERT INTO alphabet_combination (combination) VALUES (?)');
mysqli_stmt_bind_param($q, 's', $combinations);
mysqli_stmt_execute($q);

If you want for each value single INSERT so after submit in database will be next 1500 rows:

$q = mysqli_prepare($con, 'INSERT INTO alphabet_combination (combination) VALUES (?)');
mysqli_stmt_bind_param($q, 's', $combination);

foreach ($_POST['combination'] as $combination) {
    mysqli_stmt_execute($q);
}

Try this code after submission of your form:

extract($_POST);
foreach ($combination as $comb) {
    //if your table has only one field inside:
    $query = mysql_query("INSERT INTO tablename VALUES('".$comb."')");
}

Another example for another idea along with the form:

<?php
if( isset($_POST['btnsubmit']) ){
    extract($_POST);
    foreach ($sample as $samp) {
        $query = mysql_query("INSERT INTO tablename VALUES('".$samp."')");
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample</title>
</head>
<body>
    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
        <input type="text" name="sample[]" value="hello1"><br>
        <input type="text" name="sample[]" value="hello2"><br>
        <input type="text" name="sample[]" value="hello3"><br>
        <input type="text" name="sample[]" value="hello4"><br>
        <input type="text" name="sample[]" value="hello5"><br>
        <input type="submit" name="btnsubmit" value="Submit">
    </form>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM