I have a page in which user can update their posts.
I need to update the database with different query(for different Conditions).
But every time I run update using this code, image filename changes automatically (even if I have a condition). Am I doing something wrong?
if(empty($up_image)){
$up_image = $image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$up_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
$path1 = "img/$up_image";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path1)){
copy($path1, "../$path1");
}
}
else{
$error = "Unable to Update Post";
}
}
if(!empty($up_image)){
$up_image = preg_replace('/\s+/','',$up_image);
$image_size = $_FILES['image']['size'];
$allowed_img_ext = array("jpg", "jpeg", "png", "bmp");
$ext = pathinfo($up_image, PATHINFO_EXTENSION);
$trimed_img_name = pathinfo($up_image, PATHINFO_FILENAME);
if(in_array($ext, $allowed_img_ext))//check valid file extension
{
if($image_size < 2097152) {
$ren_image = substr($trimed_img_name,0,3)."".substr($title,0,11)."_".date("mj")."_".date("Y")."_".date("His").".".$ext;
$path = "img/".$ren_image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$ren_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
}
else{
$img_error = "Please Upload the Image File Size Less than 2 MB";
}
}
else{
$img_error = "Invalid Image File";
}
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path)){
copy($path, "../$path");
}
}
else{
$error = "Unable to Update Post";
}
} //End
So I removed $up_image = $image; and image = $up_image section from first query now it is working. Thanks for your comment
Related
I tried to upload video filenames and other variables to the database, but the insert statement won't work. Anyway the videofile-name and the thumbnail-filename are both uploaded to the right folders.
I've checked and there's nothing wrong with the sql statement. But why won't it work can anyone tell me?
PHP code
<?php
session_start();
if (isset($_POST['submit'])) {
$videoName = $_POST['videoName'];
$videoDesc = $_POST['description'];
$category = $_POST['category'];
$level = $_POST['level'];
$userId = $_SESSION['userId'];
$videoFile = $_FILES["videoFile"];
$videoFileName = $videoFile['name'];
$videoFileType = $videoFile['type'];
$videoFileTempName = $videoFile['tmp_name'];
$videoFileError = $videoFile['error'];
$videoFileExt = explode(".", $videoFileName);
$videoFileActualExt = strtolower(end($videoFileExt));
$videoAllowed = array("mp4", "mov", "avi");
$thumbFile = $_FILES["thumbnail"];
$thumbFileName = $thumbFile["name"];
$thumbFileType = $thumbFile["type"];
$thumbFileTempName = $thumbFile["tmp_name"];
$thumbFileError = $thumbFile["error"];
$thumbFileExt = explode(".", $thumbFileName);
$thumbFileActualExt = strtolower(end($thumbFileExt));
$thumbAllowed = array("jpg", "jpeg", "png");
if (in_array($videoFileActualExt, $videoAllowed)) {
if(in_array($thumbFileActualExt, $thumbAllowed)) {
if ($videoFileError === 0) {
if ($thumbFileError === 0) {
$videoFullName = $videoFile . "." . uniqid("", true) . "." . $videoFileActualExt;
$videoFileDestination = "../video/" . $videoFullName;
$thumbFullName = $thumbFile . "." . uniqid("", true) . "." . $thumbFileActualExt;
$thumbFileDestination = "../thumbnail/" . $thumbFullName;
include 'dbh.inc.php';
if(empty($videoName) or empty($videoDesc)) {
header("Location: ../uploadVideo.php?upload=empty");
exit();
} else {
move_uploaded_file($videoFileTempName, $videoFileDestination);
move_uploaded_file($thumbFileTempName, $thumbFileDestination);
$sql = "INSERT INTO video (filnavn, thumbnail, videoName, descript, idMusician, categoryName, idLevel) VALUES ('$videoFullName', '$thumbFullName', '$videoName', '$videoDesc', $userId, '$category', $level);";
mysqli_query($conn, $sql);
header("Location: ../uploadVideo.php?upload=success");
exit();
}
} else {
echo "You had a thumbnail error!";
exit();
}
} else {
echo "You had a video error!";
exit();
}
} else {
echo "You need to upload a proper thumbnail file type";
exit();
}
} else {
echo "You need to upload a proper video file type!";
exit();
}
} else {
}
You cannot insert or in this way in the if() condition, you must always use the logical operator as
if(empty($videoName) || empty($videoDesc))
Because of that your execution of code must have stopped at that point.
I am trying to have an Edit page that fetch the data selected by user and display them in a form. I manage to display the data from database and allow user to edit the data in the form. But my UPDATE query won't work in php. I tried echo the query and run it manual in xampp, it turns out to be ok and it was able to update manual in xampp but not in php. Can anyone help me with the codes? many thanks
this is my php coding
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_POST['btn-update']))
{
$ProdCode = mysql_real_escape_string($_POST['productCode']);
$ProdType = mysql_real_escape_string($_POST['productType']);
$ProdDes = mysql_real_escape_string($_POST['product_description']);
$ProdCol = mysql_real_escape_string($_POST['productColour']);
$ProdPrice = floatval($_POST['productPrice']);
$XSsize = mysql_real_escape_string($_POST['XSquantity']);
$Ssize = mysql_real_escape_string($_POST['Squantity']);
$Msize = mysql_real_escape_string($_POST['Mquantity']);
$Lsize = mysql_real_escape_string($_POST['Lquantity']);
$XLsize = mysql_real_escape_string($_POST['XLquantity']);
$XXLsize = mysql_real_escape_string($_POST['XXLquantity']);
if(isset($_FILES['productImg'])){
$file_name = $_FILES['productImg']['name'];
$file_size = $_FILES['productImg']['size'];
$file_tmp = $_FILES['productImg']['tmp_name'];
$file_type = $_FILES['productImg']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['productImg']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors="Please choose JPEG/PNG file.";
$errorTrigger =true;
}
if($file_size > 2097152) {
$errors='File size must be excately 2 MB';
$errorTrigger =true;
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
} }
$query = "UPDATE product SET product_code='$ProdCode', product_type='$ProdType' ,description='$ProdDes' ,colour='$ProdCol',price= '$ProdPrice',size_xs='$XSsize',size_s='$Ssize',size_m='$Msize',size_l='$Lsize',size_xl='$XLsize',size_xxl='$XXLsize' WHERE product_code='%". $ProdCode ."%'";
echo $query;
if(mysql_query($query))
{
echo "<script>
alert('Product Updated');
</script>";
}
else
{
echo mysql_error();
?>
<script>alert('Error while updating');</script>
<?php
}
}
?>
I made simple upload system with using class.upload.php and it works great while adding new into database. But i have problem when i need to edit my entry. While editing entry i don't want to edit image but it sent it blank, also if i select image again it sent it blank too. Here is my code.
Can explain my problem.
<?php require_once("conn.php");
require_once ("class.upload.php");
$catid = $_POST['catid'];
$title = $_POST['title'];
$descc = $_POST['descc'];
$keyw = $_POST['keyw'];
$message = $_POST['message'];
$Image = $_FILES['Image'];
$randnum = rand();
$foo = new upload($Image);
$filee = './Image';
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
$Image7 = $foo->file_dst_name;
if($_GET[pass] == 1)
{
if(!isset($_POST[catid]) || empty($_POST[catid])){
$hata = "Required area.";
}
if(!isset($_POST[title]) || empty($_POST[title])){
$hata = "Required area.";
}
if(!isset($_POST[descc]) || empty($_POST[descc])){
$hata = "Required area.";
}
if(!isset($_POST[keyw]) || empty($_POST[keyw])){
$hata = "Required area.";
}
if(!isset($_POST[message]) || empty($_POST[message])){
$hata = "Required area.";
}
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image='$_POST[Image]'
WHERE id='$_POST[id]'
");
$mesaj = "OK!";
}
}
$sonuc = mysql_query("select * from product WHERE id='$_GET[product]'");
$edit = mysql_fetch_array($sonuc);
$sonuc1 = mysql_query("select * from category");
$edit1 = mysql_fetch_array($sonuc1);
?>
try to change the update query
at Image='$_POST[Image]'
with Image='$Image7'
Fatih you can use a variable (i.e. $saved_image_name) instead of $POST[Image] at sql query. Set this variable to new name if uploaded else old value of db field.
...
...
$foo = new upload($Image);
$filee = './Image';
$saved_image_name = " Image "; // name of db field.
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
// Note the quotes
$saved_image_name = " '$foo->file_dst_name' ";
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
// no use anymore $Image7 = $foo->file_dst_name;
...
...
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image= $saved_image_name // note the quotes
WHERE id='$_POST[id]'
");
...
...
I got an article edit function that automatically loads in the article details when selected. I am trying to see if a file was submitted or not during the edit (when resubmitted in edit mode). If the file is not submitted keep the image url in the database unchanged, else change the image url. Somehow the image url breaks when I do not submit a file during edit.
$article_id = $_POST['article-id'];
$article_title = $_POST['article-title'];
$article_description = $_POST['article-description'];
$article_image = $_POST['thumbnail'];
$article_content = $_POST['article-content'];
if(!isset($_FILES['article-thumbnail']) &&
!$_FILES['article-thumbnail']['size'] > 0){
$query = "UPDATE article
SET article_title = '$article_title',
article_description = '$article_description',
article_content = '$article_content', published = 'NO'
WHERE article_id = '$article_id'";
if (!mysql_query($query)) {
// Handle error here
// e.g.
echo "Oh no! The query failed! Error: ".mysql_error();
}
mysql_close();
} else {
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100;
$path = "test/article_thumbnails/";
$count = 0;
$thumbnailPath = 'http://localhost:8888/test_cms/images/article-thumbnails/' .
$_FILES["article-thumbnail"]["name"];
// Loop $_FILES to exeicute all files
foreach ($_FILES['article-thumbnail']['name'] as $f => $name) {
if ($_FILES['article-thumbnail']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['article-thumbnail']['error'][$f] == 0) {
if ($_FILES['article-thumbnail']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
} else if( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ) {
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
} else { // No error found! Move uploaded files
if(move_uploaded_file($_FILES["article-thumbnail"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
$query = "UPDATE article
SET article_title = '$article_title',
article_description = '$article_description',
article_image = '$thumbnailPath',
article_content = '$article_content', published = 'NO'
WHERE article_id = '$article_id'";
if (!mysql_query($query)) {
// Handle error here
// e.g.
echo "Oh no! The query failed! Error: ".mysql_error();
}
mysql_close();
}
As you can see during the else statement the thumbnailPath is set to the url following the name of file:
$_FILES["article-thumbnail"]["name"];
What happens when I do not submit a file during the edit is it writes the url in the database without the file name. Even though it shouldn't get in the else clause?
this is my function for add and edit data, In my form when i upload image i called validateProdImage() function for upload image, but this code is not working in IE8, this code is working fine in firefox and crome.
//for add and edit product
function addEditProduct(){
$this->setGetVars();
$this->setPostVars();
if(!$this->submit || $this->submit != 1) return;
// Validate image type and image size
if($this->prod_image['name'])
$this->validateProdImage();
if($this->action == "add") {
// Check if the Product already exist
$q = "AND prod_name = '".$this->prod_name."'";
if($this->getCntProduct($q) > 0)
$this->setMessage("Product already exist!", "error");
else {
// Adding New Product
$query = "INSERT INTO tbl_product SET
prod_id = '',
prod_name = '".addslashes($this->prod_name)."',
prod_code = '".addslashes($this->prod_code)."',
prod_image = '',
prod_weight = '".addslashes($this->prod_weight)."',
prod_type = '".$this->prod_type."',
prod_desc = '".addslashes($this->prod_desc)."',
prod_price = '".$this->prod_price."',
prod_stock = '".$this->prod_stock."',
prod_status = '".$this->prod_status."'";
$this->connect->executeQuery($query, $this->connect->conn);
$this->last_insert_id = $this->connect->insert_id;
// Saving image
if($this->prod_image['name'])
$this->prod_image_name = $this->saveProductImage();
$query = "UPDATE tbl_product SET
prod_image = '".$this->prod_image_name."' WHERE prod_id =".$this->last_insert_id;
$this->connect->executeQuery($query, $this->connect->conn);
$this->setMessage("Product has been addedd successfully!", "success");
header("refresh:1; url=index.php?cnt=product&act=list&rs=1");
}
} else if($this->action == "edit") {
$image = "";
// For update image we check if new image availbale then we can call this function
if($this->prod_image['name']) {
$this->prod_image_name = $this->saveProductImage();
$image = "prod_image = '".$this->prod_image_name."',";
}
// Edit Product details
$query = "UPDATE tbl_product SET
prod_name = '".addslashes($this->prod_name)."',
prod_code = '".addslashes($this->prod_code)."',
".$image."
prod_weight = '".addslashes($this->prod_weight)."',
prod_type = '".$this->prod_type."',
prod_desc = '".addslashes($this->prod_desc)."',
prod_price = '".$this->prod_price."',
prod_stock = '".$this->prod_stock."',
prod_status = '".$this->prod_status."' WHERE prod_id = '".$this->prod_id."' LIMIT 1";
$this->connect->executeQuery($query, $this->connect->conn);
$this->setMessage("Product details has been edited successfully!", "success");
header("refresh:1; url=index.php?cnt=product&act=list&rs=1");
}
}
// Save Product Image
function saveProductImage() {
$imagename = "";
$temppath = $this->prod_image['tmp_name'];
$extention = explode("/",$this->prod_image['type']);
if(isset($this->last_insert_id))
$imagename = $this->last_insert_id."_".time().".".$extention[1];
else
$imagename = $this->prod_id."_".time().".".$extention[1];
$filepath = PRODUCT_UPLOAD_DIR.$imagename;
if($this->prod_image_name)
if(file_exists(PRODUCT_UPLOAD_DIR.$this->prod_image_name))
unlink(PRODUCT_UPLOAD_DIR.$this->prod_image_name);
move_uploaded_file($temppath,$filepath);
return $imagename;
}
Instead of
header("refresh:1; url=index.php?cnt=product&act=list&rs=1");
use
sleep(1);
header("Location: /index.php?cnt=product&act=list&rs=1");