MySQL數據庫可以用來存儲圖片,這對于一些需要使用圖片的應用來說是非常重要的。下面是使用MySQL存儲圖片的一些步驟。
1. 創建一個包含圖片的表格
CREATE TABLE images ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, image MEDIUMBLOB );
2. 使用PHP上傳圖片
<?php if(isset($_POST['submit'])){ $name = $_FILES['image']['name']; $temp_name = $_FILES['image']['tmp_name']; $img = file_get_contents($temp_name); $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 創建連接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢查連接 if ($conn->connect_error) { die("連接失敗: " . $conn->connect_error); } $sql = "INSERT INTO images (name, image) VALUES ('$name', '$img')"; if ($conn->query($sql) === TRUE) { echo "圖片上傳成功"; } else { echo "錯誤: " . $sql . "
" . $conn->error; } $conn->close(); } ?>
3. 從數據庫中獲取圖片
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 創建連接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢查連接 if ($conn->connect_error) { die("連接失敗: " . $conn->connect_error); } $sql = "SELECT image FROM images WHERE id=1"; $result = $conn->query($sql); if ($result->num_rows >0) { // 輸出數據 while($row = $result->fetch_assoc()) { echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>'; } } else { echo "0 結果"; } $conn->close(); ?>
以上是如何使用MySQL存儲圖片的簡單教程,希望對您有所幫助。