这是我当前的 preg_match_all 输出
Array
(
[0] => Array
(
[0] => 2 Sentence text here
)
)
Array
(
[0] => Array
(
[0] => 3 Sentence text here.
[1] => 4 Sentence text here.
[2] => 5 Sentence text here.
)
)
我试图将每个输出作为新行插入表中,但它认为每个 [0] [1] [2] 都是一个新列。如何将数组插入mysql?
$query = "INSERT INTO table (col1) VALUES ";
foreach ($matches as $item) {
$query .= "('".$item[0]."'),";
}
$query = rtrim($query,",");
$result = mysql_query($query);
上面显然只插入数组的第一行
最佳答案
好吧,你在另一个数组中有一个数组,所以......
$query = "INSERT INTO table (col1) VALUES ";
if(!empty($matches))
{
foreach ($matches as $item) {
foreach ($item[0] as $items) {
$query .= "('".$items."'),";
}
}
}
<小时/>
if(!empty($matches))
{
foreach ($matches[0] as $item) {
$query .= "('".$item."'),";
}
}
取决于您如何获得数组匹配。
<小时/>$query = rtrim($query,",");
$result = mysql_query($query);
这样你就会得到这个查询:
INSERT INTO table (col1) VALUES ('2 Sentence text here'), ('3 Sentence text here'), ('4 Sentence text here'), ('5 Sentence text here')
这是使用单个 INSERT 语句在一列中插入多个值的有效方法。
注意: Please, don't use mysql_* functions in new code 。它们不再维护and are officially deprecated 。请参阅red box ?了解 prepared statements相反,并使用 PDO ,或MySQLi -this article将帮助您决定哪个。如果您选择 PDO,here is a good tutorial .
关于PHP 数组向后输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221704/