简体   繁体   中英

Insert values from an array into MySQL using PHP

Assuming I have an array as follows:

$array = array('first_value', 
               'second_value', 
               'thrid_value', 'and so on');

And a Column in which I'd want to insert those values, but each value in a separate row.

Would it it be possible to do that?

Obviously there are some answers to this one would be just loop thru the array elements and for every loop execute an insert statement, but that just seems unwise.

Or given that I'd have an ID column, that would help a lot(but I don't).

The amount of data to be introduced is not terribly large so the loop is perfectly viable, I just wanna make sure there isn't some easier way to do this that I may not be aware of.

You could use prepared statements; the first query will send the SQL statement and the subsequent calls will only send the data, thereby reducing the load:

$stmt = $db->prepare('INSERT INTO mytable (colname) VALUES (?)');

foreach ($array as $value) {
    $stmt->execute(array($value));
}

If you're using PDO , such as the above example, make sure to disable prepared statement emulation.

// connect to database and store the resource in $connection
$array = array('first_value', 
               'second_value', 
               'thrid_value', 'and so on');

foreach($array as $value)
{
 $value=mysqli_real_escape_string($connection,$value);
 mysqli_query($connection,"INSERT INTO yourTABLE(columnName) VALUES('$value')");
}

You can put them all into a single INSERT statement with multiple VALUES lists.

$values = implode(',', array_map(function($v) use ($mysqli) {
    return "'" . $mysqli->real_escape_string($v) . "'"; },
  $array));
$query = "INSERT INTO yourTable (Column) VALUES $values";
$mysqli->execute($query) or die ($mysqli->error);

mysql手册进行插入 ,您可以尝试以下操作:

INSERT INTO yourtable (column_name) VALUES (value_a), (value_b), (value_c);

$array = array('first_value','second_value','third_value');

$SQL = "INSERT INTO `table` (column) VALUES('".implode("'),('",$array)."')";

OR

$values = '';
foreach($array as $val){
$values .= !empty($values)? ",('{$val}')" : "('{$val}')"; 
}

$SQL = "INSERT INTO `table` (column) VALUES{$values}";

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