gpt4 book ai didi

php - 如何在不循环执行的情况下将数组插入mysql

转载 作者:行者123 更新时间:2023-11-29 05:48:33 24 4
gpt4 key购买 nike

我目前遇到了一个问题,我想通过 pdo 将一个包含准备好的语句的数组插入到我的数据库中。我在这里找到了一些代码作为开始,但目前它只插入传递给该方法的数组 $files 中的一个文件。

$amount = count($files);

for($i=0; $i<$amount; $i++){

$dbArr=[
'path' => (string) dirname( $files[$i] ),
'name' => (string) basename( $files[$i] ),
'size' => (int) filesize($files[$i]),
'mimeType' => (string) mime_content_type( $files[$i] ),
];
}

foreach($dbArr as $k => $v ) {
$prep[':'.$k] = $v;
}

new sql();

$q = sql::$db->prepare($str = "INSERT INTO filesSrc ( " . implode(', ',array_keys($dbArr)) . ") VALUES (" . implode(', ',array_keys($prep)) . ")");

$res = $q->execute($prep);

它有效,但只插入数组之一。解决方案可能很简单,我忽略了一些东西。

最佳答案

$params = [
'path' => ':path',
'name' => ':name',
'size' => ':size',
'mimeType' => ':mineType',
];
$sql = "INSERT INTO filesSrc ( " . implode(',', array_keys($params)) . ") VALUES (" . implode(',', $params) . ")";
$amount = count($files);
$dbArrs = [];
for($i=0; $i<$amount; $i++){

$dbArrs[] = [
'path' => (string) dirname( $files[$i] ),
'name' => (string) basename( $files[$i] ),
'size' => (int) filesize($files[$i]),
'mimeType' => (string) mime_content_type( $files[$i] ),
];
}



new sql();
#todo It is recommended to use 'try catch'
$q = sql::$db->prepare($sql);
foreach ($dbArrs as $dbArr) {
foreach ($params as $key => $param) {
$q->bindParam($param, $dbArr[$key]);
}
$q->execute();
}

关于php - 如何在不循环执行的情况下将数组插入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57123826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com