gpt4 book ai didi

php - 在数据库中存储上载图像的路径

转载 作者:行者123 更新时间:2023-11-29 23:18:24 25 4
gpt4 key购买 nike

这是一个上传多张图片的脚本。如果我上载3张图像,则3张图像会存储在服务器文件夹中,但在数据库中,每个图像路径都会存储两次,因此它给出6个条目而不是3个条目

<?php
ob_start();
include('co_session.php');

if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image

$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable

$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array

if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
//echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';

$file_name_all.=$target_path."*";
$filepath = rtrim($file_name_all, '*');
//echo $filepath;
$officeid = $_GET['id'];
echo $officeid;

$str= $filepath;
$array = explode('*', $str);
foreach ($array as $item)
{

$sql="INSERT INTO officeimage (offimage,officeid,lat,lon) VALUES ('$item','$officeid','$user_latitude','$user_longitude')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
//header("Location: co_request_sent.php ");
}
mysqli_close($con);
?>


谁能指出错误

最佳答案

我建议在循环外声明“常量”,如$validextensions
然后您声明$file_extension,但在下一行中,您要做$ext[count($ext) - 1]

对于您的多次插入问题:您执行了一个foreach循环,将每个元素插入到for循环内以移动它们。

Loop #1
Move image #1
Add image #1 to Stack
Subloop
Insert image #1 from Stack
Loop #2
Move image #2
Add image #2 to Stack
Subloop
Insert image #1 from Stack
Insert image #2 from Stack
Loop #3
Move image #3
Add image #3 to Stack
Subloop
Insert image #1 from Stack
Insert image #2 from Stack
Insert image #3 from Stack


在末尾 :


图片#1已插入三次
图片#2插入了两次
图片#3插入一次


总计:6个条目

将foreach移到循环外或删除堆栈/ foreach,以在每转一圈时插入当前图像。

关于php - 在数据库中存储上载图像的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27562338/

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