MySQL数据库可以用来存储图片,这对于一些需要使用图片的应用来说是非常重要的。下面是使用MySQL存储图片的一些步骤。
1. 创建一个包含图片的表格
CREATE TABLE images (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,name VARCHAR(30) NOT NULL,image MEDIUMBLOB);
2. 使用PHP上传图片
<?phpif(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存储图片的简单教程,希望对您有所帮助。