你需要創建一個上傳功能,並保存只有你圖像的路徑被存儲。
在數據庫中創建一個包含少量列名的表:filepath,mime,size。
一個小例子:index.php
:
if(isset($_FILES['file']['name'])){
$name = $_FILES['file']['name'];
$mime = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
$tmp = $_FILES['file']['tmp_name'];
$path = 'uploads/' . $name; //maybe you should create the uploads/ folder before running the script
if(move_uploaded_file($tmp, $path)){
$db = new PDO('mysql:host=localhost;dbname=your_db_name','your_db_user','your_db_pass');
$stmt = $db->prepare('INSERT INTO your_table_name_here SET filepath=?,mime=?,size=?');
$stmt->execute([$path,$mime,$size]);
echo 'File uploaded successfully!';
}
}
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
然後你就可以抓住所有的保存路徑,並將其添加爲src
attrbuite爲你的形象。
//index.php
$stmt = $db->prepare('SELECT filepath FROM your_table_name_here');
$stmt->execute();
while($row = $stmt->fetch()){?>
<img src="<?php echo $row['filepath']; ?>" alt="image">
<?php }
但是須注意,這只是一個超級簡單的腳本,爲您的學習目的,這個代碼必須在生產模式中使用,至於是不是安全的。
存儲BLOB圖像不是個好主意,而只是保存它的路徑。 –
http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Sammitch