在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"表中。注意要替换代码中的数据库连接信息为你自己的信息。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 如何在php httpserver中集成数据库