Can't change featured image when editing blog post - php

I'm creating a PHP and SQL blog. Among other files, I have upload_file.php and edit_post.php. Every time I edit a post, it updates all the information except for the featured image. It won't upload a new featured image. Here is upload_file.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if (!empty($_FILES['post_image']['name'])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["post_image"]["name"]);
$image_name = basename($_FILES["post_image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["post_image"]["tmp_name"]);
if($check !== false) {
$file_image = "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$file_not_image = "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
$file_exists = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["post_image"]["size"] > 5000000) {
$file_too_large = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$file_not_allowed = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$file_not_uploaded = "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["post_image"]["tmp_name"], $target_file)) {
$file_uploaded = "The file ". basename( $_FILES["post_image"]["name"]). " has been uploaded.";
} else {
$file_error = "Sorry, there was an error uploading your file.";
}
}
}
}
?>
Here is edit_post.php, minus the form:
<?php include("session_start.php")?>
<?php include("upload_file.php")?>
<?php include("links.php"); ?>
<?php include("navigation.php"); ?>
<?php
if($_GET['id'] != ""){
$post_id = $_GET['id'];
$sql = "SELECT * FROM posts WHERE post_id='$post_id' AND user_name='$user_name'";
$post = mysqli_query($connection, $sql) or die(mysqli_error($connection));
}
?>
<?php
$sql = "SELECT DISTINCT post_category FROM posts WHERE user_name='$user_name'";
$cat = mysqli_query($connection, $sql) or die(mysqli_error($connection));
?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$post_title = isset($_POST['post_title']) ? $_POST['post_title'] : null;
$post_content = isset($_POST['post_content']) ? $_POST['post_content'] : null;
if($_POST['new_category']==""){
$post_category = ($_POST['choose_category']);
}else{
$post_category = ($_POST['new_category']);
}
$post_date = isset($_POST['post_date']) ? $_POST['post_date'] : null;
if (isset($image_name)){
$sql = "UPDATE posts SET post_title='$post_title', post_content='$post_content', post_category='$post_category', post_date='$post_date', post_image='$image_name' WHERE post_id='$post_id' AND user_name='$user_name'";
}else{
$sql = "UPDATE posts SET post_title='$post_title', post_content='$post_content', post_category='$post_category', post_date='$post_date' WHERE post_id='$post_id' AND user_name='$user_name'";
}
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));
header('Location: index.php');
}
?>
<?php include "footer.php";?>
How can I fix this?

I just realized the reason this wasn't working is because I forgot to put enctype="multipart/form-data" on my form!

Related

mysqli_stmt_prepare fails but file is uploaded to phpmyadmin

I have this php photo gallery, however my "mysqli_stmt_prepare" statement seems to be failing in someway. However, when I check my DB, the files that are in accordance to the upload rules, I created in my code, have been uploaded.
The message I get each time I upload a file to the DB is the one corresponding to a failed "mysqli_stmt_prepare", namely as in the code:
echo "SQL statement failed! 1"
<?php
if (isset($_POST['submit'])) {
$newFileName = $_POST['filename'];
//sets the file name to "gallery"
if (empty($_POST['filename'])) {
$newFileName = "gallery";
//adds hyphens to empty spaces
} else {
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$imageTitle = $_POST['filetitle'];
$imageDesc = $_POST['filedesc'];
$file = $_FILES['file'];
$fileName = $file['name'];
$fileType = $file['type'];
$fileTempName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png", "pdf");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 200000) {
$imageFullName = $newFileName . "." . uniqid("uniqID", false) . "." . $fileActualExt;
$fileDestination = "../gallery/" . $imageFullName;
include_once "dbh.inc.php";
if (empty($imageTitle || $imageDesc)) {
header("Location: ../gallery.php?upload=empty");
echo "You didn't include the Image Title and Image description!";
exit();
} else {
$sql = "SELECT * FROM gallerytrexatek";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed! 1";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount + 1;
$sql = "INSERT INTO gallery (titleGallery, descGallery, imgFullNameGallery, orderGallery) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed! 2";
} else {
mysqli_stmt_bind_param($stmt, "ssss", $imageTitle, $imageDesc, $imageFullName, $setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("Location: ../galleryInPHP.php?upload=success");
}
}
}
} else {
echo "File Size is way to big";
exit();
}
} else {
echo "You had an error with the file";
exit();
}
} else {
echo "The file type you tried to upload is not allowed!";
exit();
}
}
?>
I expect the file to upload without problems. It seems I am overlooking something rather simple.
Hint: There are 3 files connected to this one.
1. The gallery.php where the form exists for images to be uploaded
2. The one which is pasted here
3. the DB handler file
Do'h, there was a problem with one of the file handler files.

Profile picture only displays black box with an "X" inside

I am trying to set up a profile page where user can upload a profile picture. The problem I a having is that when the status is changed from 1 to 0 the image changes from a default profile image to a small black box with an "x" in it. Everything else works fine. I thought it might be the css but it is not. If anyone can assist, it would greatly appreciated. Thank you.
Profile.php:
<?php
$id= $_GET['id'];
$sql = "SELECT * FROM user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$sqlImg = "SELECT * FROM profileImg WHERE id='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div class='userProfileImage'>";
if ($rowImg['status'] == 0 ) {
echo "<img src='images/profile".$id.".jpg'>";
} else {
echo "<img src='images/profile_default.jpg'>";
}
echo "<p>".$row['first']."</p>";
echo "</div>";
}
}
} else {
echo "There are no users yet!";
}
uploadProfile.php:
<?php
session_start();
include '../dbh.php';
$id = $_SESSION['id'];
$userID = $id;
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileERROR = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'gif', 'png', 'mov', 'mpeg4', 'mp4', 'avi', 'wmv', 'mpegps', 'flv', '3gpp', 'webm');
if (in_array($fileActualExt, $allowed)) {
if ($fileERROR === 0) {
if ($fileSize < 500000) {
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = '../uploads/'.$fileNameNew;
$sql = "UPDATE profileImg SET status=0 WHERE id='$id'";
$result = mysqli_query($conn, $sql);
move_uploaded_file($fileTmpName, $fileDestination);
header("Location: ../profile.php?id=$userID");
} else {
echo "Your file is too large";
}
} else {
echo "There was an error uploading your file";
}
} else {
echo "You cannot upload files of this type";
}
}
?>
Files are being uploaded to uploads as line below
$fileDestination = '../uploads/'.$fileNameNew;
and img src is
echo "<img src='images/profile".$id.".jpg'>";
Please update you code.
Edit: you are allowing multiple extensions to be uploaded and on profile.php single extension is used to load the picture.

I can't display my blob pictures from mysql db in php

In my application, I store the pictures as blob in the mysql db.
Now I want to display the pictures in my web application.
Now the Problem is:
The images are not displayed. Just a small sign. I'm not getting any error message.
I don't know how to update my project, to display the pictures
Model function:
public function create($fileName, $fileType, $fileSize, $fileContent, $gallery){
$query = "INSERT INTO $this->tableName (name, type, size, content, gallery_ID) VALUES (?, ?, ?, ?, ?)";
$statement = ConnectionHandler::getConnection()->prepare($query);
$statement->bind_param('ssisi', $fileName, $fileType, $fileSize, $fileContent, $gallery);
$success = $statement->execute();
if (!$success) {
throw new Exception($statement->error);
}
}
public function listByID($galleryID){
$query = "SELECT * from $this->tableName where gallery_ID = ?";
$statement = ConnectionHandler::getConnection()->prepare($query);
$statement->bind_param('i', $galleryID);
$statement->execute();
$result = $statement->get_result();
if (!$result) {
throw new Exception($statement->error);
}
$rows = array();
while ($row = $result->fetch_object()) {
$rows[] = $row;
}
return $rows;
}
Controller Method:
public function doAddPhoto(){
$fileName = $_FILES['fileToUpload']['name'];
$fileSize = $_FILES['fileToUpload']['size'];
$fileType = $_FILES['fileToUpload']['type'];
$tmpName = $_FILES['fileToUpload']['tmp_name'];
$gallery = $_SESSION['gallery'];
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($_FILES['fileToUpload']['size'] <= 0 ){
echo '<div class="alert alert-danger" id="messsage" role="alert">No Picture selected</div>';
}
else if ($_FILES["fileToUpload"]["size"] > 4194304) {
echo '<div class="alert alert-danger" id="messsage" role="alert">File to big</div>';
}
else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo '<div class="alert alert-danger" id="messsage" role="alert">Sorry, only JPG, JPEG, PNG & GIF files are allowed.</div>';
}
else {
$fp = fopen($tmpName, 'r');
$fileContent = fread($fp, filesize($tmpName));
fclose($fp);
if(!get_magic_quotes_gpc()){
$fileName = addslashes($fileName);
}
$photoModel = new PhotoModel();
$photoModel->create($fileName, $fileType, $fileSize, $fileContent, $gallery);
}
header('location: /gallery/ListGalleriesPerUserOverview');
}
public function showPhotosPerUser(){
if (!isset($_SESSION ['loggedin']) || $_SESSION ['loggedin'] != true)
{
header('location: /');
return;
}
else{
$view = new View('gallery');
$galleryID = $_SESSION['gallery'];
$photoModel = new PhotoModel($galleryID);
$photos = $photoModel->listByID($galleryID);
$view->photos = $photos;
$view->display();
}
}
HTML:
<form action="/photo/doAddPhoto" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="uploadBtn">
</form>
<?php
foreach ($photos as $photo){
$content = $photo->content;
echo '<div class="col-md-3 portfolio-item">
<a href="#">
<img src="data:image/jpeg;base64,'. base64_encode($content) .'" />
</a>
</div>';
}
?>

Save image url path in DB columns [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i am updating name , email in DB of registered user through php form. its working fine.
class.usr.php
public function update($uname,$email, $tax)
{
try {
$stmt = $this->conn->prepare('UPDATE tbl_users SET userName = ?, userEmail = ? , tax = ? WHERE userID = ? ');
$stmt->execute(array($uname,$email, $tax , $_SESSION['userSession']));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
form
<form action="profile.php" method="POST" enctype="multipart/form-data">
Name :
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" /><br>
Image
<input type="file" name="photo" id="fileSelect"><br>
<input type="submit" name="submit" value="Save" />
</form>
form related code to save in db
<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
after this, now i am uploading an image to folder through same php form successfully with below code.
<?php
if(isset($_FILES["photo"]["error"])){
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "";
}
?>
now images are just saving in folders, what i need is i want that image path to save in database and assign that image path to uploaded user in database. so that one registered user can update the existing image, but not upload one more image.
i tried below code , but not working:
<?php
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
$tax= $full_path;
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "";
}
?>
db columns : userName, userEmail, tax , photo
with help of google i done all above, i am new to php, so please kindly help me.
Here is another solution:
First of all execute this query manually to add the new column:
ALTER TABLE `tbl_users` ADD `photo` VARCHAR(255) NOT NULL ;
Then this is the php code:
<?php
$dbConn = new Database();
$dbConn->dbConnection();
$user_home = new USER();
function uploadUserPhoto($uid) {
global $dbConn;
if(isset($_FILES["photo"]["error"])) {
if($_FILES["photo"]["error"] > 0) {
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
$userDir = $uid;
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)) {
if(!is_dir('upload/'.$uid)) {
mkdir('upload/'.$uid);
}
$photoname = time().$uid.'_photo'.'.'.$ext;
// delete all the files in this directory
$files = glob('upload/'.$uid.'/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
// Upload the photo
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $uid . '/'. $photoname);
$updateData = array(':userID' => $uid, ':photo' => $photoname);
$stmt = $dbConn->conn->prepare("UPDATE tbl_users SET photo=:photo WHERE userID=:uid");
$stmt->execute($updateData);
echo "Your file was uploaded successfully.";
} else {
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else {
echo "";
}
}
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
uploadUserPhoto($uid);
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
There is $dbConnection variable which is the connection to the DB but because I don't know the rest of your code you should replace it with your proper db connection variable.
The photo of the user is saved in photo column in tbl_users and for every user is created sub dir in uploads dir. The subdir is the userID. So for example for user with userID = 1 its upload path will be uploads/1/<filename>.
File name is generated dynamically - this avoids caching of uploaded photo with the same name for example ... and it is better approach.
You have to make a change in code for displaying the photo because now its filename is in the DB and there is subdir in uploads (which is the userID of the user)
Add new function for saving files and use global php var $_FILES
1
Add new column to your DB to store file path, let's name it photo
2
Add new functions for your user class:
<?php
class User {
...
const PATH_PHOTOS = '/path/to/photo/folder/';
const BASE_URL = 'http://YOUR_DOMAIN_NAME:YOUR_PORT/YOUR_PATH/';
public function add_photo($file)
{
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$file['new_name'] = uniqid(rand(), true) . ".$ext";
if (!$this->_upload_file($file))
return false;
return $this->_remove_previous_photo()->_add_file_to_db(self::PATH_PHOTOS . basename($file['new_name']));
}
protected function _remove_previous_photo()
{
$photo = $this->get_photo();
if ($photo)
unlink($photo);
return $this;
}
public function get_photo()
{
global $_SESSION;
$stmt = $this->conn->prepare('SELECT photo FROM tbl_users WHERE userID = ? ');
$stmt->execute(array($_SESSION['userSession']));
$result = $stmt->fetch();
return reset($result);
}
public function get_photo_url()
{
$pathInfo = pathinfo($this->get_photo());
$last_dir = end(explode(DIRECTORY_SEPARATOR, $pathInfo['dirname']));
return self::BASE_URL . "$last_dir/" . basename($this->get_photo());
}
protected function _upload_file($file)
{
$uploadfile = self::PATH_PHOTOS . $file['new_name'];
return move_uploaded_file($file['tmp_name'], $uploadfile);
}
protected function _add_file_to_db($file_path)
{
try {
$stmt = $this->conn->prepare('UPDATE tbl_users SET photo = ? WHERE userID = ? ');
return $stmt->execute(array($file_path, $_SESSION['userSession']));
} catch (PDOException $e) {
echo '<p class="bg-danger">' . $e->getMessage() . '</p>';
}
}
...
}
?>
3
The main file should look like this:
<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid) && $user_home->add_photo($_FILES['photo']))
{
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
Hope this helps

undefined index at sending POST data

I got some problems and it looks like I can't find any way to work around it. I tried use isset for each POST data, but while it would solve all the problems, the data won't be added.
I'll leave you the HTML code and PHP, so maybe you will be able to help me debugging this code.
adm_prod.php (the html page which handles the form)
<form method="POST" action="includes/prod-add.php">
Product Name<br>
<input type="text" name="Name"><br>
Price:<br>
<input type="number" name="Price"><br>
Product Description<br>
<input type="text" name="Description"><br>
Photo<br>
<input type="file" name="Photo"><br>
</br>
<button name="submit">Add Product</button>
</form>
prod-add.php (php file which handles the inserting/validating info)
<?php
include 'databaseConnection.php';
$name = $_POST['Name'];
$price = $_POST['Price'];
$description = $_POST['Description'];
$target_dir = "images-uploads/";
$target_file = $target_dir . basename($_FILES['Photo']['name']);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
if(isset($_POST['submit'])) {
$check = getimagesize($_FILES['Photo']['tmp_name']);
if($check !== false) {
$uploadOk = 1;
} else {
echo "The File Is not an image";
$uploadOk = 0;
}
}
if(file_exists($target_file)) {
$filename = $_FILES['Photo']['name'];
$extension = end(explode(".",$filename));
$name = rand(pow(10, 7), pow(10, 8)-1);
$newfilename = $name . "." .$extension;
$uploadOk = 1;
echo "Image already exists. Image Name changed to " . $newfilename;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
$uploadOk = 0;
echo "Sorry, only JPG, PNG and JPEG are accepted";
}
if ($uploadOk == 0) {
echo " Sorry, your product was not added, please check the error";
$fileupload = 0;
} else {
if (move_upload_file($_FILES['Photo']['tmp_name'], $target_file)) {
$fileupload = 1;
$imagePath = basename( $_FILES['Photo']['name']) . "." . $imageFIleType;
}
}
if($fileupload == 1) {
$addProd = "INSERT INTO meniu (name, price, description, path) VALUES ('$name','$price','$description','$imagePath')";
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
if ($conn->query($addProd) == TRUE) { ?>
<script>
window.alert("Product: <?php echo $name; ?> has been added successfully ");
</script>
<?php } else { ?>
<script>
window.alert("Error: <?php echo $conn->error; ?>");
</script>
<?php }
}
?>
I'm sorry if the code is not very clear, I'm still learning PHP. Usually I don't have any problem like this, but it's the first time I'm using image upload.
Basically, in the database I wanna introduce Name, Description, Price, Photo Path. The path should be something like ../uploads/photoname.extension .
Thanks for help.
The error is caused when the form is submitted without filling all the fields first. So, you need to check if the $_POST variables are set by firstly checking if the form has been submitted.
Also, add this to your form tag in the html enctype="multipart/form-data".
$name=$price=$description="";
if($_SERVER['REQUEST_METHOD']=="POST") {
//if the form has been submitted, initialize the values.
$name = $_POST['Name'];
$price = $_POST['Price'];
$description = $_POST['Description'];
$target_dir = "images-uploads/";
$target_file = $target_dir . basename($_FILES['Photo']['name']);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
:
//rest of the code
:
}
Inside that check if the file was uploaded with it:
if(isset($_POST['submit']) && isset($_FILES['Photo'])) {
$check = getimagesize($_FILES['Photo']['tmp_name']);
}
Encapsulate the entire process inside the if statement.
Also, as told by tadman, use parameterized queries using Prepared Statements or PDO in your mysql queries.

Categories