Can't post image file into given directory with $_FILES function - php

I have two pretty much similar cases of adding image files to directory and they both work, but I don't know why this one doesn't, since it's done on the same principles.
And since it's not pasting into the "show" directory, the output is following:
add-album.php
<?php
include "config.php";
if (isset($_POST["submit_album"])) {
$album = $_POST["album_name"];
$album_prikazna = $_POST["album_prikazna"];
$photo = $_FILES["album_prikazna"]["album_name"];
$upload = "show/".$photo;
$add_album = $conn->query("INSERT INTO gallery_albums (album_name, album_prikazna) VALUES ('$album', '$album_prikazna')");
move_uploaded_file($_FILES['album_prikazna']['album_name'], $upload);
header("Location: fotogalerije.php?add_album_action=successfull");
}
?>
fotogalerije.php
<div class="container">
<!--Images-->
<div class="">
<h3>Arhivi</h3>
<form method="post" action="add-album.php">
<label>Dodaj novi album:</label><br>
<input type="text" name="album_name" /> <input type="submit" name="submit_album" value="Add" /><br>
<input type="file" class="mt-3" name="album_prikazna">
</form><br>
<?php
if (isset($_GET["add_album_action"])) {
if ($_GET["add_album_action"] == "successfull") { ?>
Nov album dodan!<br><br>
<?php }
}
?>
<div class="">
<?php
$albums = $conn->query("SELECT * FROM gallery_albums");
while ($album_data = $albums->fetch_assoc()) {
$photos = $conn->query("SELECT * FROM gallery_photos WHERE album_id = ".$album_data["album_id"]."");
?>
<div class="p-0 m-0">
<img src="<?php echo $album_data['album_prikazna']; ?>" width="125" class="p-1" />
<a href="view-album.php?album_id=<?php echo $album_data["album_id"] ?>">
<?php echo $album_data["album_name"];
$imagePrikazna = $album_data["album_prikazna"];
?>
(<?php echo $photos->num_rows; ?>)</a>
<?php }
?>
</div>
</div>
</div>
</div>
<!--!Images-->

Related

How do I remain the image when I update edit form?

I can update image on my application but if I have to update same picture again and again when I click edit button on edit section...so I want to remain current image when I update edit section without any change for image.
I tried to put these codes below but it didn't work....
if(empty($image)){
$selected_image = $db->prepare("SELECT * FROM posts WHERE post_id={$the_post_id}");
$selected_image->execute(array($the_post_id));
$selected_images = $selected_image->fetch();
}
Does anyone give some advise or concern for my codes?
I really appreciate!
Thank you!
<!-- Edit -->
<?php
if(isset($_REQUEST['edit_post_id'])){
$the_post_id = $_REQUEST['edit_post_id'];
$posted = $db->prepare("SELECT * FROM posts WHERE post_id = $the_post_id ");
$posted->execute(array($the_post_id));
$posted_p = $posted->fetch();
}
?>
<?php
if(isset($_POST['edit_post'])){
$edit_posts = $db->prepare("UPDATE posts SET post_image=?, post_contents=? WHERE post_id ='{$the_post_id}' ");
$edit_posts->execute(array(
$image = date('YmdHis') . $_FILES['image']['name'],
$_POST['post_contents']
));
move_uploaded_file($_FILES['image']['tmp_name'], './images/' . $image);
if(empty($image)){
$selected_image = $db->prepare("SELECT * FROM posts WHERE post_id={$the_post_id}");
$selected_image->execute(array($the_post_id));
$selected_images = $selected_image->fetch();
}
header('Location: index.php');
exit();
}
?>
<!-- Edit form -->
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<div class="well">
<form action="" method="post" enctype="multipart/form-data">
<div>
<label for="summernote">Edit</label>
<textarea class="form-control" name="post_contents" id="summernote" col="30" rows="10"><?php echo htmlspecialchars($posted_p['post_contents'], ENT_QUOTES); ?></textarea>
</div>
<div class="form-group">
<label for="post_image">Image</label>
<input type="file" name="image" >
<img width="100" src="./images/<?php echo $posted_p['post_image']; ?>" >
</div>
<span class="form-group">
<p><input class="btn btn-primary" type="submit" name="edit_post" value="Edit"></p>
</span>
</form>
</div>
</div>
</div>
</div>
you should update your query so it sets post_image only if $_FILES['image'] it exists
this should work:
<?php
if(isset($_POST['edit_post'])){
$image = $_FILES['image'] ? date('YmdHis') . $_FILES['image']['name'] : "";
$edit_posts = $db->prepare(
"UPDATE posts SET post_contents=?". empty($image) ?: ", post_image=?" ."WHERE post_id ='{$the_post_id}' "
);
$params = array(
$_POST['post_contents']
);
if (!empty($image)) {
$params[] = $image;
}
$edit_posts->execute($params);
move_uploaded_file($_FILES['image']['tmp_name'], './images/' . $image);
if(empty($image)){
$selected_image = $db->prepare("SELECT * FROM posts WHERE post_id={$the_post_id}");
$selected_image->execute(array($the_post_id));
$selected_images = $selected_image->fetch();
}
header('Location: index.php');
exit();
}
?>

Hiding the form if the field in database is null in php

Hi i have a registration form in my website.if the particular field in the db is null then the form should not be displayed to the user.Here if the payment_category_upload field is empty then the form should not displayed to the user otherwise the form should be displayed.
<?php include 'includes/db.php';
$sql = "SELECT * FROM users WHERE username = '$_SESSION[user]' AND user_password = '$_SESSION[password]' AND payment_category_upload!='' ";
$oppointArr =array();
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0)
{
if(isset($_POST['submit_user'])|| isset($_POST['save_users']))
{
$formsubmitstatus = isset($_POST['submit_user'])?1:0;
if($_FILES["affidavits_upload"]["tmp_name"]!="")
{
$pname = rand(1000,10000)."-".str_replace("-"," ",$_FILES["affidavits_upload"]["name"]);
$affidavits_upload = $_FILES["affidavits_upload"]["tmp_name"];
$uploads_dir = '../admin/images/uploads';
move_uploaded_file($affidavits_upload, $uploads_dir.'/'.$pname);
}
else
{
$pname = $_POST['hid_affidavits_upload'];
}
$id= $_POST['users_id'];
$ins_sql = "UPDATE users set affidavits_upload='$pname',status='3',affidavitsupload_submit_status='$formsubmitstatus' WHERE users_id = $id";
$run_sql = mysqli_query($conn,$ins_sql);
$msg = 'Your Application successfully submitted. ';
$msgclass = 'bg-success';
}
else
{
$msg = 'Record Not Updated';
$msgclass = 'bg-danger';
}
}
else
{
echo "Please make the payment to enable Affidavits";
}
?>
FORM :
<form class="form-horizontal" action="affidavits.php" method="post" role="form" enctype="multipart/form-data" id="employeeeditform">
<?php if(isset($msg)) {?>
<div class="<?php echo $msgclass; ?>" id="mydiv" style="padding:5px;"><?php echo $msg; ?></div>
<?php } ?>
<input type='hidden' value='<?=$id;?>' name='users_id'>
<div class="form-group">
<label for="affidavits_upload" class="col-sm-4 control-label">Affidavits Upload</label>
<div class="col-sm-8">
<input type="hidden" value="<?php echo $oppointArr['affidavits_upload'];?>" name="hid_payment_category_upload">
<input type="file" name="affidavits_upload" id="affidavits_upload">
<?php if(!empty($oppointArr['affidavits_upload'])){?>
<div>
<?php echo $oppointArr['affidavits_upload'];?>
</div>
<?php }?>
<span class="text" style="color:red;">Please upload PDF Format Only</span>
</div>
</div>
<div class="col-sm-offset-2">
<?php if($oppointArr['affidavitsupload_submit_status'] == 0){ ?>
<button type="submit" class="btn btn-default" name="save_users" id="save_users">Save</button>
<button type="submit" class="btn btn-default" name="submit_user" id="subject">Submit Application</button>
<?php } ?>
</div>
</form>
//Add this Css class
.hiddenBlock {
display:none
}
<div class="<?php echo isset(test_field)?"":"hiddenBlock"; ?>">
<form>...<form>
</div>
You can do it like this for your field.

Picture does not appear after successfully uploading it

so today I was trying to upload photo from admin file to user file. One thing I discovered is that my code works fine, but something is a little bit wrong I don't know where. When I successfully uploaded the picture, the picture didn't appear. But it successfully been uploaded. Could you help me out?
This is the code I used to upload the picture
<?php
require_once ('db/database.php');
if(isset($_POST['submit']))
{
$name = basename($_FILES['file_upload']['name']);
$t_name = $_FILES['file_upload']['tmp_name'];
$dir = 'fotovid';
$kat = $_POST['kat'];
if(move_uploaded_file($t_name, $dir."/".$name))
{
mysqli_select_db($koneksi, 'koneksi_oop');
$query = "INSERT INTO gallery (id_gambar, kat_gambar, nama_gambar, path) VALUES ('', $kat, '$name', 'fotovid/$name')";
$res = mysqli_query($koneksi, $query);
echo "Berhasil upload foto";
} else {
echo "Gagal upload foto";
}
}
?>
<div class="wrapper">
<div class="panel"">
<div align="center" style="padding-top: 100px;">
<!-- <div class="container1" style="background-color: none;margin-bottom: 235px;">
<label for="file-input">Upload Video</label>
<input type="file" accept=".mp4,.mkv" id = "file-input" style="background-color: none; width: 300px; "><br/>
<script type="text/javascript" src = "assets/js/videoJS.js"></script>
</div> -->
<form action="inputfoto.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload" /><br/>
<label>Kategori</label>
<input type="text" name="kat"><br/>
<input type="submit" name="submit" value="Upload">
</form>
</div>
</div>
</div>
While this is the class where I call 2 categories from database, which is 'Foto' and 'Video'.
<?php
include ('admin/db/database.php');
$query = "SELECT * FROM kategori_gambar";
$res = mysqli_query($koneksi, $query);
while ($row=mysqli_fetch_array($res))
{
?>
<div>
<fieldset style="margin:0px 40px 100px 40px;">
<legend>
<a href="keluar_gambar.php?kat_gambar=<?= $row['id'];?>">
<?php
echo $row['nama'];
?>
</a>
</legend>
</fieldset>
</div>
<?php
}
?>
And the last one is where the output should comes out.
$query = "SELECT * FROM gallery WHERE kat_gambar =".$_GET['kat_gambar'];
$res = mysqli_query($koneksi, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
while($row=mysqli_fetch_array($res))
{
?>
<img src = "<?php echo $row['path']; ?>" width='300px' height= "200px" /><br/>
<?php
}
?>
This is what happened when I tried to insert the image
enter image description here
enter image description here
enter image description here
enter image description here
I think there is a permission issue. could you please show us the output of the following code.
$row=mysqli_fetch_array($res)
and also check the folder where you tried to upload.

PHP MySQL not updating for CRUD app

I'm attempting to add the update function to my CRUD application. Essentially it uses the database specified, and uses the 'id' from the index.php page, which is 'productID' from the database. In another part of the application, a store management feature is included with the same skeleton Update page and works perfectly.
The database (Product) contains productID(PK), productName, productPrice, storeID(FK), productDate, productComments, productQuantity, and productPortion.
I'm certain it's within the PHP script, likely around the UPDATE command after using a few error checks but I can't seem to figure out what might be the main issue.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update an Item</h3>
</div>
<form class="form-horizontal" action="update.php" method="post">
<input type="hidden" name="productID" value="<?php echo $id ?>">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Item</label>
<div class="controls">
<input name="productName" type="text" placeholder="Product Name" value="<?php echo !empty($productName)?$productName:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="productPrice" type="number" step="any" placeholder="Price" value="<?php echo !empty($productPrice)?$productPrice:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($storeError)?'error':'';?>">
<label class="control-label">Store</label>
<div class="controls">
<select name="storeID" class="form-control">
<option value="">Select Store</option>
<?php $pdo=D atabase::connect(); $sql='SELECT * FROM Store ORDER BY storeName DESC' ; foreach ($pdo->query($sql) as $row) { $selected = $row['storeID']==$storeID?'selected':''; echo '
<option value="'. $row['storeID'] .'" '. $selected .'>'. $row['storeName'] .'</option>'; } Database::disconnect(); ?>
</select>
<?php if (!empty($storeError)): ?>
<span class="help-inline"><?php echo $storeError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($dateError)?'error':'';?>">
<label class="control-label">Date</label>
<div class="controls">
<input name="productDate" type="date" step="any" placeholder="Date" value="<?php echo !empty($productDate)?$productDate:'';?>">
<?php if (!empty($dateError)): ?>
<span class="help-inline"><?php echo $dateError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($commentsError)?'error':'';?>">
<label class="control-label">Comments</label>
<div class="controls">
<input name="productComments" type="text" placeholder="Comments" value="<?php echo !empty($productComments)?$productComments:'';?>">
<?php if (!empty($commentsError)): ?>
<span class="help-inline"><?php echo $commentsError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($quantityError)?'error':'';?>">
<label class="control-label">Quantity</label>
<div class="controls">
<input name="productQuantity" type="number" placeholder="Quantity" value="<?php echo !empty($productQuantity)?$productQuantity:'';?>">
<?php if (!empty($quantityError)): ?>
<span class="help-inline"><?php echo $quantityError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($portionError)?'error':'';?>">
<label class="control-label">Portion</label>
<div class="controls">
<input name="productPortion" type="number" placeholder="Portion" value="<?php echo !empty($productPortion)?$productPortion:'';?>">
<?php if (!empty($portionError)): ?>
<span class="help-inline"><?php echo $portionError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div>
<!-- /container -->
</body>
</html>
PHP
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$priceError = null;
$storeError = null;
$dateError = null;
$quantityError = null;
$portionError = null;
// keep track post values
$id = $_POST['id'];
$storeID= $_POST['storeID'];
$productName = $_POST['productName'];
$productPrice = $_POST['productPrice'];
$productQuantity = $_POST['productQuantity'];
$productPortion = $_POST['productPortion'];
$productComments = $_POST['productComments'];
$productDate = $_POST['productDate'];
//error displayed for creation errors
$valid = true;
if (empty($productName)) {
$nameError = 'Please enter the name of the product';
$valid = false;
}
if (empty($productPrice)) {
$priceError = 'Please enter a price';
$valid = false;
}
if (empty($storeID)) {
$storeError = 'Please enter a store';
$valid = false;
}
if (empty($productDate)) {
$dateError = 'Please enter the purchase date';
$valid = false;
}
if (empty($productComments)) {
$commentsError = 'Please enter any comments';
$valid = false;
}
if (empty($productQuantity)) {
$quantityError = 'Please select the quantity';
$valid = false;
}
if (empty($productPortion)) {
$portionError = 'Please enter the portion';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Product SET productName=?, productPrice=?, storeID=?, productDate=?,
productComments=?, productQuantity=?, productPortion=? WHERE productID=?";
$q = $pdo->prepare($sql);
$q->execute(array($productName,$productPrice,$storeID,$productDate,
$productComments,$productQuantity,$productPortion,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Product WHERE productID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$productName = $data['productName'];
$productPrice = $data['productPrice'];
$storeID = $data['storeID'];
$productQuantity = $data['productQuantity'];
$productPortion = $data['productPortion'];
$productComments = $data['productComments'];
$productDate = $data['productDate'];
Database::disconnect();
}
?>
Having a quick look at your code you are sending the form data via $_POST and on the php script checking $_GET then grabbing the id from $_REQUEST. Try changing
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
to
if ( !empty($_POST['id'])) {
$id = $_POST['id'];
}
Hope that helps!
Thanks Donniep!
I found that the answer was actually related to the POST values after being submitted. My impression was that I could still use the value from the GET call of 'id', but I instead needed to use the actual ID value from the product DB instead. The solution turned out to be:
// keep track post values
$id = $_POST['id'];
Needed to be changed to:
// keep track post values
$id = $_POST['productID'];

edit data from mysql db

I am working on a CMS and seem to be having issues currently with my edit code and I can't figure out what the problem is for the life of me, when I submit to edit, everything goes through as if the edit was successful, however nothing is ever changed or submitted to the database.
I have been trying many different things and nothing seems to make any difference, I am totally lost on this one.
editarticle.php
<?php
ob_start();
session_start();
include_once('includes/connection.php');
include_once('includes/news.php');
include_once('includes/functions.php');
$article = new Article;
$funct = new UserFunctions;
if (isset($_SESSION['logged_in'])) {
$articles = $article->fetch_all();
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
if (empty($title) or empty($content)) {
$error = 'All fields are required!';
header('Location: index.php?p=editarticle');
} else {
global $pdo;
$query = $pdo->prepare('UPDATE articles SET article_title = ?, article_content = ? WHERE article_id=?');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $id);
$query->execute();
header('Location: index.php');
}
}
//check if an article is selected to be edited
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare("SELECT * FROM articles WHERE article_id = ?");
$query->bindValue(1, $id);
$query->execute();
$rows = $query->fetchAll();
//get the article title and content to put in edit inputs
foreach ($rows as $row) {
$id = $row['article_id'];
$title = $row['article_title'];
$content = $funct->br2nl($row['article_content']);
}
?>
<!-- POST -->
<div class="post">
<div class="topwrap">
<div class="userinfo pull-left">
<div class="avatar">
<img src="images/avatar.jpg" alt="" />
<div class="status green"> </div>
</div>
<div class="icons">
<img src="images/icon1.jpg" alt="" /><img src="images/icon4.jpg" alt="" /><img src="images/icon5.jpg" alt="" /><img src="images/icon6.jpg" alt="" />
</div>
</div>
<div class="posttext pull-left">
<h2>Edit Article</h2>
<!-- add Article form start !-->
<form action="editarticle.php" method="post" autocomplete="off">
<input type="text" name="title" value="<?php echo $title; ?>" /><br /><br />
<textarea rows="10" cols="87" name="content" /><?php echo $content; ?></textarea>
<!-- add article form break !-->
</div>
<div class="clearfix"></div>
</div>
<div class="postinfobot">
<div class="dateposted pull-right">
<!-- add article form continue !-->
<input class="btn btn-primary" type="submit" value="Submit Changes" />
</form>
<!-- add article form end !-->
</div>
<div class="clearfix"></div>
</div>
</div>
<!-- POST -->
<?php
} else {
?>
<!-- POST -->
<div class="post">
<div class="topwrap">
<div class="userinfo pull-left">
</div>
<div class="posttext pull-left">
<h2>Select an Article to Edit</h2>
<?php foreach ($articles as $article) { ?>
<?php echo $article['article_id']; ?> - <?php echo $article['article_title']; ?><br />
<?php } ?>
</div>
<div class="clearfix"></div>
</div>
<div class="postinfobot">
<div class="dateposted pull-right"> </div>
<div class="clearfix"></div>
</div>
</div>
<!-- POST -->
<?php
}
} else {
header('Location: index.php');
}
?>
includes/news.php
class Article {
public function fetch_all() {
global $pdo;
$article_status = 1;
$query = $pdo->prepare("SELECT * FROM articles WHERE article_status = ? ORDER BY article_timestamp DESC");
$query->bindValue(1, $article_status);
$query->execute();
return $query->fetchAll();
}
public function fetch_data($article_id) {
global $pdo;
$article_status = 1;
$query = $pdo->prepare("SELECT * FROM articles WHERE article_id = ? AND article_status = ?");
$query->bindValue(1, $article_id);
$query->bindValue(2, $article_status);
$query->execute();
return $query->fetch();
}
}
I am getting back into PHP for the first time in 10 years and have been doing a lot of C# development over the last 2 years. I am finding it very difficult to troubleshoot issues with PHP thus far, as I have gotten very little or no error messages to work with (not even in the error_log on my host).
Any ideas why this isn't submitting the changes to the database?
The page is seting $id with get when loaded. But then again you are posting the data to self by creating a new instance of post this new post doesn't know anything about $id
So you need to explicitly pass $id (unless it is a session variable, where you can use $_session variable to retrieve it) as a hidden value in your form
try adding this to form:
<input type="hidden" value="<?php echo $id;?>">
As #noob pointed out, yu need to pass the article id in the first form, because your UPDATE statement need it.
Therefore:
if (isset($_POST['title'], $_POST['content'], $_POST['id'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
$id= $_POST['id'];
And in your form:
<form action="editarticle.php" method="post" autocomplete="off">
<input type="hidden" value="<?php echo $id;?>">
<input type="text" name="title" value="<?php echo $title; ?>" /><br /><br />
<textarea rows="10" cols="87" name="content" /><?php echo $content; ?></textarea>
<!-- add article form break !-->
</div>
<div class="clearfix"></div>
</div>
<div class="postinfobot">
<div class="dateposted pull-right">
<!-- add article form continue !-->
<input class="btn btn-primary" type="submit" value="Submit Changes" />
</form>

Categories