如何使用php在数据库中存储多个图像名称?
这段代码使用html和php上传多个图像 这是我的如何使用php在数据库中存储多个图像名称?,php,html,file-upload,Php,Html,File Upload,这段代码使用html和php上传多个图像 这是我的HTML代码: <form action="<?php echo site_url('account/add_gallery1');?>" method="post" enctype="multipart/form-data" > <input type="hidden" name="user_id" value="<?php echo $profile->id;?>" id="user
HTML
代码:
<form action="<?php echo site_url('account/add_gallery1');?>" method="post" enctype="multipart/form-data" >
<input type="hidden" name="user_id" value="<?php echo $profile->id;?>" id="user_id"/>
<input type="file" name="userfile[]" multiple>
<button type="submit" class="btn btn-default save_change_btn">upload photo</button>
</form>
if($_FILES['userfile']['name'] != "") {
if(isset($_FILES['userfile'])) {
$j = 0; // Variable for indexing uploaded image.
$target_path = DOCUMENT_ROOT."uploads/test/"; // Declaring Path for uploaded images.
for ($i = 0; $i < count($_FILES['userfile']['name']); $i++) {
// Loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['userfile']['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["userfile"]["size"][$i] < 2000000)
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $target_path)) {
// If file moved to uploads folder.
$cpt = count($_FILES['userfile']['name'][$i]);
for($i=0; $i<$cpt; $i++) {
$images = $_FILES['userfile']['name'];
}
$names= implode(',', $images);
$data = array(
'user_id' => $user_id,
'image_name' => $names
);
//print_r($data);die;
$this->user_model->insert_gallery_images($data);
} else {
echo $j. ')'."File Not Moved.";
}
} else {
echo $j. ')'."Invalid file Size or Type";
}
}
}
}
在模型中:
function insert_gallery_images($var)
{
$this->db->insert('dbc_gallery_images',$var);
}
问题:我的问题是如何从$\u文件['userfile']['name'][$I]
中获取图像名称,并在数据库中存储一个图像名称?
例如,我有一个表galery_images,它有三个字段id、user_id和image_name。
从这个问题中,我得到了图像名,但它的格式是这样的
id user_id image_name
----- -------- ------------
1 12 coach_1.jpg,coach_2.jpg,coach_3.jpg,coach_4.jpg
但我想要这样的图像存储
id user_id image_name
----- -------- ------------
1 12 coach_1.jpg
2 12 coach_2.jpg
3 12 coach_3.jpg
4 12 coach_4.jpg
直接将图像存储在db上是一种不好的做法,例如,您应该将文件存储在hdd上,并仅将路径保存在db上。好的。。我接受你的建议,你能解释一下我现在如何存储图像吗?我相信你可以将图像作为blob存储在mysql中,但正如@Claudio King所说的,最好将图像保存在文件夹中,并将路径存储在数据库中。因此,请澄清您现在询问的是如何上传图像并将路径存储在数据库中是的,我想将图像路径存储在数据库中请尽快给我解决方案。