10/10/2018, 09:43
Update hình ảnh trong PHP và Mysql
Mình đang làm đồ án bằng PHP và Mysql, trong trang dành cho admin có phần cập nhật dữ liệu, dữ liệu dạng text thì mình cập nhật được nhưng đến hình ảnh thì sao mình làm hoài không được,
Bạn nào đã có kinh nghiệm về vấn đề này xin chỉ giúp, mình đang rất cần, cảm ơn mọi người!
Bạn nào đã có kinh nghiệm về vấn đề này xin chỉ giúp, mình đang rất cần, cảm ơn mọi người!
Bài liên quan
Đưa bạn đoạn code để tham khảo:
<?
include("../connect/config.php");
if($_POST['submit'])
{
$title=$_POST['title'];
$file_name=$_FILES['filename']['name'];
$file_path=$_FILES['filename']['tmp_name'];
$new_path="upload/images/".$file_name;
$uploaded_file=move_uploaded_file($file_path,$new_ path);
$query="insert into table (title, images) values ('$title', '$new_path' )";
$sql=mysql_query($query);
}
else
{
print EOF
<form method="post" enctype="multipart/form-data">
<input type="text" name="title" />
<input type="file" name="filename" />
<input type="submit" name="submit" value="Nhập" />
</form>
EOF;
}
?>
Còn update, đơn giản chỉ là cách thay đổi giá trị của biến $new_path
để mình mô tả sơ cái mình đang bí nhe,
mình có trang thông tin sản phẩm, khi click vào nút sửa sẽ gọi đến trang cập nhật sản phẩm với mã sản phẩm của trang thông tin sp,
Tại trang Cập nhật, mình làm thế này:
<?php
if(isset($_REQUEST[id]))
{
$ma_cong_trinh = $_REQUEST["id"];
}
$result = mysql_query("select * from tbl_cong_trinh_cong_nghiep where Ma_cong_trinh = '$ma_cong_trinh'");
if(mysql_num_rows($result)<>0)
{
while($rows=mysql_fetch_row($result))
{
$ma_cong_trinh = $rows[0];
$ten_cong_trinh = $rows[1];
$tom_tat = $rows[2];
$noi_dung = $rows[3];
$hinh = $rows[4];
}
}
?>
sau đó mình echo dữ liệu lên để người dùng sửa dữ liệu,
và mình có một thẻ
<input type="file" name="file" id="file" /> tương ứng với nút Browse
lúc này mình muốn cho người dùng chọn một hình khác và mình sẽ vào CSDL xóa hình cũ đi và update hình mới đó vào CSDSL và cũng upload hình mới đó vào Folder images luôn
bạn nói thêm phần này giùm mình nhe,
thanks nhiều!
Mỗi 1 mẩu tin sẽ bao gồm 1 nút sửa.
Tại trang form_sua.php
$id=$_GET['id'];
$query="selec * form table where id='$id'";
$sql=mysql_query($query);
while($result=mysql_fecth_aray($sql))
{
$id=$result['id'];
$title=$result['title'];
$img_path=result['img_path'];
}
<form>
<input type="text" name="title" <? if($_POST['title']) echo $_POST['title'] ; else echo $title; ?> />
<input type="file" name="filename" />
<input type="submit" value="submit" name="submit" />
</form>
if($_POST['submit'])
{
if($_FILES['filename']['name'])
{
$file_name=$_FILES['filename']['name'];
$file_path=$_FILES['filename']['tmp_name'];
$new_path="upload/images/".$file_name;
$img_path=$new_path;
$uploaded_file=move_uploaded_file($file_path,$new_ path);
}
else
{
$img_path=$img_path
}
}
update table set title='$title', img_path='$img_path'
Code như trên và có chỉnh sửa tý xíu để xóa cái ảnh.