如何在PHP和mysql数据库中上传和插入多个图像

时间:2017-06-19 16:00:01

标签: php android mysql base64

我是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;

}      ?&GT;

1 个答案:

答案 0 :(得分:0)

你需要某种循环...我在下面的例子中所做的只是制作一个名为$ 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";
}
}