使用mysql在php中检索并上传图像 [英] Retrieve and upload image in php using mysql
本文介绍了使用mysql在php中检索并上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在从数据库检索图像时遇到问题.这是将图像上传到数据库的代码:
I have a problem in retrieving an image from a database. Here is the code that uploads the image to the database:
<form method="post" action="index2.php" enctype="multipart/form-data">
<input type="file" name="drimg2"/>
<input type="submit" name="submit2" value="Save"/>
</form>
<?php
if(isset($_POST['submit2'])) {
$con=mysql_connect("localhost","root","root");
mysql_select_db("test",$con);
$imgname1=$_FILES['drimg2']['name'];
echo $imgname1;
$imageextension1 = substr(strrchr($imgname1,'.'), 1);
if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
}
if (($imageextension1= "jpg") && ($imageextension1= "jpeg") && ($imageextension1= "gif") && ($imageextension1 = "png") && ($imageextension1 = "bmp")) {
$query1=mysql_query("INSERT INTO store set image='$imgname1'");
$action = move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1);
die('not Uploded');
}
}
?>
现在,我想检索数据库中的所有图像;为此,我正在使用以下代码:
Now I want to retrieve all the images in the database; for this I am using the following code:
<?php
$query1="select * from store";
$fetch=mysql_query($query1);
while ($rows=mysql_fetch_array($fetch)) {
echo "<img src='images/".$rows['image']."' />";
}
?>
推荐答案
您不应使用旧的mysql_ *函数,而应使用PDO或mysqli.这是一种更清洁,更安全的方式来做您想要的事情.
You should not be using the old mysql_* functions and use PDO or mysqli instead. Here is a much cleaner and securer way of doing what you want.
<?php
/**
* A Simple class to handle your database requests
* related to your image storage ect
*/
class image_model{
private $db;
function __construct($db){
$this->db = $db;
}
function add($img_name){
$sql = "INSERT INTO store (image) VALUES (:value)";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':value', $img_name, PDO::PARAM_STR);
$stmt->execute();
}
function get_all(){
$sql = "SELECT image FROM store";
return $this->db->query($sql)->fetchAll();
}
//Perhaps use in future
function get_image($id){
$sql = "SELECT image FROM store WHERE id=:id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
return $result->fetchAll();
}
}
//Connect safely to your database...
try{
$db = new PDO("mysql:host=localhost;dbname=test", 'root', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to mySQL server. Details:'.$e->getMessage());
}
//Create an instance of the image model above
$img_model = new image_model($db);
//Boom...Handle the upload
if($_SERVER['REQUEST_METHOD']=='POST'){
if ($_FILES["img"]["error"] > 0){
echo "Error: ".$_FILES["img"]["error"]."<br />";
}else{
$img = getimagesize($_FILES["img"]["tmp_name"]);
$allowed = array('image/jpeg','image/gif','image/png','image/bmp');
//Width and height must be more then 0 pixles and mime must be in allowed array
if($img[0] > 0 && $img[1] > 0 && in_array($img['mime'],$allowed)){
if(is_uploaded_file($_FILES["img"]["tmp_name"])){
//Clean image name
$img_name = preg_replace('/[^a-zA-Z0-9.-]/s', '_', basename($_FILES["img"]["name"]));
//move image to folder
move_uploaded_file($_FILES["img"]["tmp_name"],"images/".$img_name);
//Add image to db using a method from the image model
$img_model->add($img_name);
}
}else{
echo "Error: Unknown extension. Only jpg, bmp and gif files are allowed. Please hit the back button on your browser and try again.<br />";
}
}
}
//Your form
?>
<h1>Upload image</h1>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="img"/>
<input type="submit" name="submit" value="Save"/>
</form>
<?php
//Access your image model in a simple way and get all images
foreach($img_model->get_all() as $row){
echo '<img src="images/'.$row['image'].'" /><br />';
}
?>
这篇关于使用mysql在php中检索并上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文