使用 PHP 向 MySQL 写入图片涉及以下几个基础概念:
以下是一个使用 PHP 和 MySQLi 向数据库写入图片的示例代码:
<!DOCTYPE html>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
$image = $_FILES['image']['tmp_name'];
$image_name = $_FILES['image']['name'];
$image_size = getimagesize($image);
if ($image_size == false) {
echo "File is not an image.";
exit;
}
$sql = "INSERT INTO images (name, size, data) VALUES ('$image_name', '$image_size[0]x$image_size[1]', ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $image_data);
$image_data = file_get_contents($image);
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo "Image uploaded successfully.";
} else {
echo "Error uploading image.";
}
$stmt->close();
}
$conn->close();
?>
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
size VARCHAR(20) NOT NULL,
data LONGBLOB NOT NULL
);
php.ini
文件中调整 upload_max_filesize
和 post_max_size
参数。getimagesize
函数检查文件是否为图片。希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云