从数据库中的路径显示图像

时间:2014-12-14 17:06:59

标签: php mysql image upload

我想显示我上传的图像并将图像的路径保存在MySQL数据库中。

以下是我用来上传图片并在数据库中保存表格路径的所有代码:

HTML表单:

<!DOCTYPE html>
<html>

<body>


<form action="processfangstrapport.php" enctype="multipart/form-data" method="post">

<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>
<input name="billed1" type="file" accept="image/jpeg">
</td>
</tr>

<tr>
<td>
<input name="Upload Now" type="submit" value="Upload Image">
</td>
</tr>
</tbody></table>
</form>
</body>
</html>

我的进程php:     

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fiskerirapporter";

//Opretter forbindelse til databasen
$conn = new mysqli($servername, $username, $password, $dbname);
//Check forbindelse
if ($conn->connect_error) {
    die("Forbindelse mislykkedes: " . $conn->connect_error);
}

    function GetImageExtension($imagetype)
     {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case 'image/bmp': return '.bmp';
           case 'image/gif': return '.gif';
           case 'image/jpeg': return '.jpg';
           case 'image/png': return '.png';
           default: return false;
       }
     }

if (!empty($_FILES["billed1"]["name"])) {

    $file_name=$_FILES["billed1"]["name"];
    $temp_name=$_FILES["billed1"]["tmp_name"];
    $imgtype=$_FILES["billed1"]["type"];
    $ext= GetImageExtension($imgtype);
    $imagename=date("d-m-Y")."-".time().$ext;
    $target_path = "images/".$imagename;

if(move_uploaded_file($temp_name, $target_path)) {

    $query_upload="INSERT into images_tbl (images_path,submission_date) VALUES 

('".$target_path."','".date("Y-m-d")."')";
    mysqli_query($conn, $query_upload) or die("error in $query_upload == ----> ".mysql_error());  

}else{

   exit("Error While uploading image on the server");
} 
echo "Din fangstrapport er nu oprettet.";
}
$conn->close();
?>

我的数据库表的结构:

CREATE TABLE images_tbl(
id INT NOT NULL AUTO_INCREMENT unique,
images_path VARCHAR(200) NOT NULL,
submission_date DATE
);

2 个答案:

答案 0 :(得分:0)

要做到这一点,您只需从数据库中获取所需的路径,并在HTML图像标记src中使用该路径:

echo '<img src="$imagePathFromDatabase" ... >';

要从数据库中获取图像,我们只需要SELECT查询,类似于:

SELECT images_path FROM images_tbl WHERE images_path='imagePathYouWant' LIMIT 1;

答案 1 :(得分:0)

将表数据加载到$result并根据您的要求对以下查询应用修改。

    foreach ($result as $value){
     $path = 'http://address-upto-the-image-directory/'.$value[imagepath];
     echo "<img src='".$path."' />";
    }

此处imagepath是您在表格中存储路径的字段名称。