【发布时间】:2014-09-11 14:57:40
【问题描述】:
我使用此代码上传多个图像上传现在我需要将图像路径存储在 SQL 数据库中以进行检索我只想将路径存储在数据库中我使用多个图像上传并存储在文件夹中
class Upload_Rename {
const ALLOWED_TYPES = "jpg,gif,png";
public static function generate_new_name($extension, $uppercase = true, $prefix = '', $sufix = '') {
$new_name = $prefix . uniqid() . '_' . time() . $sufix;
return ($uppercase ? strtoupper($new_name) : $new_name) . '.' . $extension;
}
public static function check_and_get_extension($file) {
$file_part = pathinfo($file);
$allowed_types = explode(",", Upload_Rename::ALLOWED_TYPES);
if (!in_array($file_part['extension'], $allowed_types)) {
throw new Exception('Not ok.. bad bad file type.');
}
return $file_part['extension'];
}
public function upload($file, $target_destination) {
if (!isset($file['tmp_name'])) {
throw new Exception('Whaaaat?');
}
$_name = $file['name'];
$_tmp = $file['tmp_name'];
$_type = $file['type'];
$_size = $file['size'];
$file_extension = '';
try {
$file_extension = Upload_Rename::check_and_get_extension($_name);
} catch (Exception $e) {
throw new Exception('Ops.. file extension? what? ' . $e->getMessage());
}
$new_name = Upload_Rename::generate_new_name($file_extension, true, 'whaat_', '_okey');
$destination = $target_destination . DIRECTORY_SEPARATOR . $new_name;
return move_uploaded_file($_tmp, $destination);
}
public function multiple_files($files, $destination) {
$number_of_files = isset($files['tmp_name']) ? sizeof($files['tmp_name']) : 0;
$errors = array();
for ($i = 0; $i < $number_of_files; $i++) {
if (isset($files['tmp_name'][$i]) && !empty($files['tmp_name'][$i])) {
try {
$this->upload(array(
'name' => $files['name'][$i],
'tmp_name' => $files['tmp_name'][$i],
'size' => $files['size'][$i],
'type' => $files['type'][$i]
), $destination);
} catch (Exception $e) {
array_push($errors, array('file' => $files['name'][$i], 'error' => $e->getMessage()));
}
}
}
print_r($errors);
}
}
if ($_FILES) {
$upload = new Upload_Rename();
$destination = 'upload/';
$upload->multiple_files($_FILES['myfile'], $destination);
$path = $upload->multiple_files($_FILES['myfile'], $destination);
}
$mysql_hostname = "";
$mysql_user = "";
$mysql_password = "";
$mysql_database = "";
$tbl_name="";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
// get the value
$name=$path;
// Insert data into mysql
$sql="INSERT INTO $tbl_name(path,)VALUES('$name',)";
$result=mysql_query($sql);
?>
<form method="post" enctype="multipart/form-data">
<?php for ($i = 0; $i < 10; $i++): ?>
file: <input type="file" name="myfile[]"><br>
<?php endfor; ?>
<input type="submit">
</form>
我如何在 SQL 中存储文件路径并使用该路径显示在另一个 php 页面中
【问题讨论】:
标签: php sql image forms upload