gpt4 book ai didi

php - 如何在PHP和mysql数据库中上传和插入多张图片

转载 作者:行者123 更新时间:2023-11-30 21:57:24 24 4
gpt4 key购买 nike

我是 PHP 的初学者。我在 base64String 中编码了一些图像。所有图像都在指定文件夹中成功解码。我的问题是我只能在数据库中记录一个图像/路径。有人帮我想出 PHP 将所有图像路径插入数据库中的一行。

这是php代码

 <?PHP
if(isset($_POST['image']))
{
$image = $_POST['image'];
$identity = $_POST['id'];
$username = $_POST['username'];

//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);

$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";

if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";

$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";

mysqli_query($conn, $sql);

}
else{
echo "uploaded_failed";
}
exit;
}
else{
echo "images_not_in";
exit;

} ?>

最佳答案

您需要某种循环……我在下面的示例中所做的只是创建一个名为 $imagesArr 的数组,而不是创建一个名为 image 的变量。我在 imagesArr 上添加了一个 foreach 循环,因此它将运行您为输入到该数组的每个图像编写的代码。我还在最后杀死了导出,因为那样会停止循环。这应该有效

 <?PHP
if(isset($_POST['image']))
{
//$image = $_POST['image']; - I commented this out
$imagesArr = array('image1.jpeg','image2.jpeg','image3.jpeg'); //etc. put all of your images here into this array
$identity = $_POST['id'];
$username = $_POST['username'];
foreach ($imagesArr as $key => $image) {
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);

$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";

if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";

$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";

mysqli_query($conn, $sql);

}
else{
echo "uploaded_failed";
}
}
else{
echo "images_not_in";
}
}

关于php - 如何在PHP和mysql数据库中上传和插入多张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44635122/

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