Hi there,
I’ve got a script that displays the product details from a database using an ID it gets from the url.
and looking to see if my questions can be answered or even if they are the right solution…
-
The form will always update inputs that the user might not have updated. is there a better way to update the table without updating everything? Maybe check to see what variable has been changed and if so, submit?
-
Like above the user won’t always need to update the image associated with the product, but my current code to support a ‘no image chosen’ type update is crude and i know this can be handled better…
-
the current code over has holes, like I have an else statement but with no output and my only reason to have it, there is when I remove it, it breaks…
ultimately im asking for what im doing wrong, and then i can go away read more about it and improve it…
Thank you…
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$name_of_book = trim($_POST['name']);
$des = trim($_POST['des']);
$pr = trim($_POST['pr']);
$cdate = date("Y-m-d");
$pid = trim($_POST['pid']);
//it doesnt matter which variable is updated by the user as it will get updated
//!! Can we do it so if the variable is the same as whats in the databate base it doesnt update?
if($name_of_book || $des || $pr){
//Update in table product
$stmt = $db_con->prepare("UPDATE product SET name=:en,
des=:ds, pr=:pr, cdate=:cd WHERE pid=:id");
$stmt->bindParam(":en", $name_of_book);
$stmt->bindParam(":ds", $des);
$stmt->bindParam(":pr", $pr);
$stmt->bindParam(":cd", $cdate);
$stmt->bindParam(":id", $pid);
$stmt->execute();
$form_feedback = "<p>Details of this book has been updated<p>";
}
//some times the image wont be updated by the user
//!!(needs to be cleaned up)
if (empty($_FILES['fileToUpload']['name'])) {
echo '';
}elseif(isset($_FILES["fileToUpload"]["name"])) {
$allowed_ext = array("jpg","png","jpeg","gif");
$ext = end(explode('.', $_FILES["fileToUpload"]["name"]));
if(in_array($ext, $allowed_ext)){
if($_FILES["fileToUpload"]["size"]<500000){
$name = md5(rand()) . '.' . $ext;
$path ="../img/".$name;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $path);
header("location:upload-v1.php?pid=".$pid."&&file-name=".$name."");
//Get the id so it knows where to update
$pid = trim($_GET['pid']);
$pid = filter_var($pid, FILTER_VALIDATE_INT);
$mg = "../img/".$name;
//insert in table product
$stmt = $db_con->prepare("UPDATE product SET img=:mg WHERE pid=:id");
$stmt->bindParam(":mg", $mg);
$stmt->bindParam(":id", $pid);
$stmt->execute();
}
}else{
echo '<script>alert("not the right image file")</script>';
}
}else{
echo '<script>alert("Big Image File")</script>';
}
}else{
//!! A file doesnt have to be selected.
//echo '<script>alert("Please select file")</script>';
}
;?>