存储图像名称

Storing image name

我目前正在将图像直接存储到数据库中。我了解到将图像存储到数据库不是一个好主意,相反我应该将图像上传到目录并将文件名插入数据库。这就是我将图像上传到目录的方式。

<?php

$newImageSubmitted = isset( $_POST['new-image'] );
if ( $newImageSubmitted ) 
{
    $output = upload();
}
return $output;
/function upload()
{
include_once "Uploader.class.php";

$uploader = new Uploader( "image-data" );
$uploader->saveIn("img");
$fileUploaded = $uploader->save();
if ( $fileUploaded )
 {

$out = "<span class='rare'>Image uploaded success!!!..</span>";

} else {
$out = "something went wrong";
}
return $out;
}

我的表格如下:

<form method='post' action='upload.php' enctype='multipart/form-data' >
<label>Find a jpg image to upload</label>
<input type='file' name='image-data' accept='image/jpg'/>
<input type='submit' value='upload' name='new-image' />
</form>

现在如何将图像名称存储到数据库??:

$db = new mysqli("localhost", "root","","rec");

if ($db->connect_error) {
    die("Connection failed this is the error: " . $db->connect_error);
}

$stmt = $db->prepare("INSERT INTO records (image) VALUES (?)");
if($stmt)
{
    $stmt>bind_param("b",$newImageSubmitted);
    $stmt->execute();
    echo"<center>Image path stored.</center>";
}

如果需要,这里是uploader.class.php。

<?php

class Uploader {
private $filename;
private $fileData;
private $destination;

public function __construct( $key ) {
$this->filename = $_FILES[$key]['name'];
$this->fileData = $_FILES[$key]['tmp_name'];
}
public function saveIn( $folder ) {
$this->destination = $folder;
}
public function save(){
$folderIsWriteAble = is_writable( $this->destination );
if( $folderIsWriteAble ){
$name = "$this->destination/$this->filename";
$succes = move_uploaded_file( $this->fileData, $name );
} else {
trigger_error("cannot write to $this->destination");
$succes = false;
}
return $succes;
}
}

这样做一个小调整
public function save(){
$folderIsWriteAble = is_writable( $this->destination );
if( $folderIsWriteAble ){
 $name = "$this->destination/$this->filename";
// new code
 if($succes = move_uploaded_file( $this->fileData, $name )){
return $name; 
}     
} else {
trigger_error("cannot write to $this->destination");
$succes = false;
}
return $succes;
}

然后在调用页面中进行小调整,例如:-

$fileUploaded = $uploader->save();
if ( $fileUploaded )
 {
   $insert="Insert into images (img_filename) values (?)";
   $stmt=$con->prepare($insert);
   $stmt->bind_param('s', $fileUploaded);
   $stmt->execute();

$out = "<span class='rare'>Image uploaded success!!!..</span>";

} else {
$out = "something went wrong";
}

在您最后的代码中,用上传图片的路径填充 $newImageSubmitted 变量。

$fileUploaded 从你的第一部分看似乎是一个对象,它可能提供一个 getFilename 方法或类似的方法。

为了帮助您,您必须提供更多代码。你的 Uploader-Class 是什么样子的?

-- 更新--

在保存方法中创建您的上传器-Class return $name

$name = "$this->destination/$this->filename";
$succes = move_uploaded_file( $this->fileData, $name );

如果成功:

return $name;