如何将数组存储到多个mysql行?

时间:2014-04-17 17:24:57

标签: php mysql arrays insert

我想生成一个文件夹中所有图像文件的索引并将其保存到mysql列" picID":

使用scandir获取文件:

$images = scandir("./", 1);
// print_r($images);

将数组发送到MySQL(进入专栏" picID") - 但是如何?

最后它应该是sg。像这样:

| id | picID      |   A N D  N O T :  | id | picID                    |
|----|------------|                   |----|--------------------------|
| 1  | DSC237.jpg |                   | 1  | DSC237.jpg, DSC947.jpg   |
| 2  | DSC947.jpg |                   | .. | ..                       |

解决方案:我修改了Patricks的答案以实现我的目标:

$link = mysqli_connect("host", "user", "pass", "db") or die(mysqli_error($link));
$images = "('" . implode( scandir("./", 1), "'),('") . "')";
// Result is: ('a'),('b'),('c') -> VALUES ('a'),('b'),('c')
mysqli_query($link, "INSERT INTO `tablename` (picID) VALUES $images");

2 个答案:

答案 0 :(得分:1)

foreach($images as $img) {
    $mysql->query("INSERT INTO `table` (picID) VALUES ('$img')");
}

更好的是,可能需要一些调整:

function insertIntoDB($dir) {
    foreach(scandir($images) as $img) {
        if(is_dir($img)) {
            insertIntoDB($dir);
        } else {
            $mysql->query("INSERT INTO `table` (picID) VALUES ('$img')");
        }
    }
}

多次插入的更好方式:

Batch inserts with PHP

MySQLi注入信息:

How can I prevent SQL injection in PHP?

答案 1 :(得分:1)

$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$images = "('" . implode( scandir("./", 1), "'),('") . "')";
mysqli_query($link, "INSERT INTO `table` (picID) VALUES $images");