简体   繁体   English

使用PHP将数组中的值插入MySQL

[英]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. 显然,对此有一些答案,就是循环遍历数组元素,并为每个循环执行一个insert语句,但这似乎是不明智的。

Or given that I'd have an ID column, that would help a lot(but I don't). 或者考虑到我会有一个ID列,这会有所帮助(但我没有)。

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: 第一个查询将发送SQL语句,随后的调用将仅发送数据,从而减少了负载:

$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. 如果您使用的是PDO ,例如上面的示例,请确保禁用准备好的语句仿真。

// 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列表的单个INSERT语句中。

$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}";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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