在PHP中,可以通過以下步驟將圖片上傳到數據庫:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
<?php
// 連接到數據庫
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 檢查是否有文件被上傳
if(isset($_FILES['image'])){
$file = $_FILES['image'];
// 獲取上傳的文件名和臨時文件路徑
$fileName = $file['name'];
$fileTemp = $file['tmp_name'];
// 讀取文件內容并將其轉換為二進制數據
$fp = fopen($fileTemp, 'r');
$content = fread($fp, filesize($fileTemp));
$content = addslashes($content);
fclose($fp);
// 將文件內容插入到數據庫中
$sql = "INSERT INTO images (name, content) VALUES ('$fileName', '$content')";
if ($conn->query($sql) === TRUE) {
echo "Image uploaded successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
}
// 關閉數據庫連接
$conn->close();
?>
CREATE TABLE images (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
content LONGBLOB NOT NULL
)
以上代碼將上傳的圖片的文件名和內容保存在數據庫中的"images"表中。注意要替換代碼中的數據庫連接信息為你自己的信息。