简体   繁体   English

PHP 'For Each' 将行从数组或字符串插入 mysql

[英]PHP 'For Each' Insert rows into mysql from array or string

I am trying to insert multiple rows into a table based on the array...with each $value being each of the comma separated values.我正在尝试根据数组将多行插入到表中...每个 $value 是每个逗号分隔值。

I know this is NOT the best way or even correct way to do this - just trying to get some guidance on how to achieve this the right way.我知道这不是最好的方法,甚至不是正确的方法 - 只是试图获得一些关于如何以正确的方式实现这一目标的指导。

$someArray=array(96,97,98,99,100,101,103,105);
foreach($someArray as $value){ 

$sql = "INSERT INTO bid_package(user_company) VALUES('".$value."');";
echo $sql;
echo "<br />";


 INSERT INTO bid_package(user_company) VALUES('96');
 INSERT INTO bid_package(user_company) VALUES('97');
 INSERT INTO bid_package(user_company) VALUES('98');
 INSERT INTO bid_package(user_company) VALUES('99');
 INSERT INTO bid_package(user_company) VALUES('100');
 INSERT INTO bid_package(user_company) VALUES('101');
 INSERT INTO bid_package(user_company) VALUES('103');
 INSERT INTO bid_package(user_company) VALUES('105');

You can put multiple lists of values in a single INSERT :您可以在单个INSERT放置多个值列表:

$values = implode(', ', array_map(function($val) {
    return "($val)";
    }, $someArray));
$sql = "INSERT INTO bid_package (user_company) VALUES $values;";

This will create a query that looks like this:这将创建一个如下所示的查询:

INSERT INTO bid_package (user_company) VALUES (96), (97), (98), (99), (100), (101), (103), (105);

If you were using PDO, it would be better to use a prepared statement, to prevent SQL-injection.如果您使用的是 PDO,最好使用准备好的语句,以防止 SQL 注入。

$values = implode(', ', array_fill(0, count($someArray), "(?)"))
$sql = "INSERT INTO bid_package (user_company) VALUES $values;"
$stmt = $conn->prepare($sql);
$stmt->execute($someArray);

First, you should be using prepared statements instead of inserting the variable directly into the query.首先,您应该使用准备好的语句,而不是将变量直接插入到查询中。 Here is one way of doing what you are attempting.这是您尝试的一种方法。

$mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb'); // your mysqli handle

$stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)"); // prepare your query

//bind value as a reference
$stmt->bind_param('s', $val);

//define values
$someArray=array(96,97,98,99,100,101,103,105);

//loop through values
foreach($someArray as $val) {
    //execute statement
    $stmt->execute();
}

If you are ever passing data to a query, you should use prepared statements.如果您曾经向查询传递数据,则应该使用准备好的语句。

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

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