Php 将多个图像文件阵列插入数据库
我正在创建一个库存表格,其中包括多达20个图像文件。当上传图像到服务器时,我需要更改名称,并将其插入数据库,以便在网站旋转木马上工作。名称更改为OK,并上传到servers文件夹。我似乎遇到的问题是,如果我选择了所有的图像,它就工作得很好,但是如果我选择较少的图像(即:1、2、3、4等),它就会崩溃。我可能看得太过明显了。任何帮助-任何想法 我在这里Php 将多个图像文件阵列插入数据库,php,mysql,Php,Mysql,我正在创建一个库存表格,其中包括多达20个图像文件。当上传图像到服务器时,我需要更改名称,并将其插入数据库,以便在网站旋转木马上工作。名称更改为OK,并上传到servers文件夹。我似乎遇到的问题是,如果我选择了所有的图像,它就工作得很好,但是如果我选择较少的图像(即:1、2、3、4等),它就会崩溃。我可能看得太过明显了。任何帮助-任何想法 我在这里 <?php if(Input::exists()) { if(Token::check(Input::get('token'))
<?php
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
try {
if(!empty($_FILES['image']['name'][0])) {
$files = $_FILES['image'];
$i = 0;
$uploaded = array();
$failed = array();
$allowed = array('gif', 'png', 'jpg', 'jpeg');
foreach($files['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if(in_array($file_ext, $allowed)) {
if($file_error === 0) {
if($file_size <= 2097152) {// 2MB
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = 'assets/uploads/' . $file_name_new;
if(move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
$image = ($i === 0) ? 'image' : 'image_' . $i;
$i++;
} else {
$failed[$position] = "[{$file_name}] failed to upload";
}
} else {
$failed[$position] = "[{$file_name}] is too large";
}
} else {
$failed[$position] = "[{$file_name}] errored with code [{$file_error}]";
}
} else {
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed";
}
}
}
$insert = DB::getInstance()->insert('stock', array(
'image' => $uploaded[0],
'image_1' => $uploaded[1],
'image_2' => $uploaded[2],
'image_3' => $uploaded[3],
'image_4' => $uploaded[4],
'image_5' => $uploaded[5],
'image_6' => $uploaded[6],
'image_7' => $uploaded[7],
'image_8' => $uploaded[8],
'image_9' => $uploaded[9],
'image_10' => $uploaded[10],
'image_11' => $uploaded[11],
'image_12' => $uploaded[12],
'image_13' => $uploaded[13],
'image_14' => $uploaded[14],
'image_15' => $uploaded[15],
'image_16' => $uploaded[16],
'image_17' => $uploaded[17],
'image_18' => $uploaded[18],
'image_19' => $uploaded[19]
));
} catch(Exception $e) {
die($e->getMessage());
}
}
}
?>
请在for循环中添加一个检查:
foreach($files['name'] as $position => $file_name) {
$uploaded[$position] = '';
if(!empty($file_name)) {
//your code here
}
}
我已经尝试过了,但它仍然没有向dbalth中添加任何条目,尽管它确实会生成一个错误通知:未定义的偏移量:在插入之前检查$upload数组内容。它的每个元素都应该包含一个字符串或一个空字符串。确保DB table列接受空字符串或null。哈哈哈,我不敢相信这是真的,我的DB设置为NONE而不是null。。啊!!谢谢你的帮助:-)@John所以接受答案吧。下面是如何返回此处,并对勾号/复选标记执行相同操作,直到它变为绿色,然后对您询问的所有其他问题执行该操作,在哪里找到解决方案。这会通知社区,找到了解决方案。否则,其他人可能会认为问题仍然悬而未决,并可能希望发布(更多)答案。(免费)帮助是双向的,就像“搔我的背,我也会搔你的背”——)
foreach($files['name'] as $position => $file_name) {
$uploaded[$position] = '';
if(!empty($file_name)) {
//your code here
}
}