By way of practicing I am building my own blog. Just to learn about PHP, MySQL and there structure. All goes well, but am running into an UPDATE problem. Let's say I have created a post with title, content and an image. Now, when I go to the page to edit my post I change my title ( not touching the content or image ). After running the update query my image that I uploaded before is gone. If I edit the post and upload a new image all is fine. I hope this makes it clear ( not so good at the jargon.. ) So, when editing, if i do not upload a new image the current image dissapears when updating the post. Here is the code:
if(isset($_FILES['post_image'])){
$errors= array();
$file_name = $_FILES['post_image']['name'];
$file_size =$_FILES['post_image']['size'];
$file_tmp =$_FILES['post_image']['tmp_name'];
$file_type=$_FILES['post_image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['post_image']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"post_images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
if(isset($_POST['EditPost'])) {
$post_id=$_GET['id'];
$post_title = $_POST['post_title'];
$post_content = $_POST['post_content'];
$post_cat_id = $_POST['post_cat_id'];
$post_tags = $_POST['post_tags'];
$post_template = $_POST['post_template'];
$post_image = $_FILES['post_image']['name'];
$sql = "UPDATE posts SET post_template=?, post_title=?, post_content=?, post_tags=?, post_image=?, post_cat_id=? WHERE post_id=?";
$query = $db->prepare($sql);
$query->execute(array($post_template,$post_title,$post_content,$post_tags,$post_image,$post_cat_id,$post_id));
$succes_update = '<div class="alert alert-success" role="alert">Uw post is ge-update!</div>';;
}
$id=$_GET['id'];
$result = $db->prepare("SELECT posts.post_id, posts.post_template, posts.post_title, posts.post_content, posts.post_tags, posts.post_image, posts.post_cat_id, categories.cat_id, categories.cat_title FROM posts INNER JOIN categories ON posts.post_cat_id=categories.cat_id WHERE post_id= :userid ");
$result->bindParam(':userid', $id);
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
?>
<div class="col-md-8">
<h2>Edit this Post</h2>
<?php
if(isset($succes_update)){
echo $succes_update;
}?>
<form action="" method="POST" enctype="multipart/form-data">
Post Title<br>
<input type="text" class="form-control" name="post_title" value="<?php echo $row['post_title']; ?>"><br>
Post Content<br>
<textarea style="width:100%; height:200px" class="form-control" n name="post_content"><?php echo $row['post_content']; ?></textarea><br>
Post Image<br>
<?php if(!empty($row['post_image'])) {?><img width="400px" src="post_images/<?php echo $row['post_image']; ?>"/><?php } else { echo " <em>There is no image set here</em>"; } ?><br><br>
<input type="file" name="post_image" /><br><br>
Post Template<br>
<input type="text" class="form-control" name="post_template" value="<?php echo $row['post_template']; ?>"><br>
<br>
Post Tags - (comma seperated)<br>
<input type="text" class="form-control" name="post_tags" value="<?php echo $row['post_tags']; ?>"><br>
Post Category<br>
<select name="post_cat_id">
<option selected><?php echo $row['cat_id']; ?> = <?php echo $row['cat_title']; ?></option>
<?php
$result = $db->prepare("SELECT DISTINCT cat_id, cat_title FROM categories WHERE parent_id > 0");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
echo "<option>". $row['cat_id'] . " = " . $row['cat_title'] . "</option>";
}
?>
</select><br><br>
<input type="submit" class="btn btn-primary" value="Edit this Post" name="EditPost" />
</form>
The reason for this is that in the EditPost section you simply take whatever is in the post_image file upload control. If you did not select a new file for the post, then this control will not have any content, thus it will override the existing post_image value with an empty string.
If a post must have an image, then check in the EditPost section if post_image has content at all and if not, then leave it out from the update statement.
If you do not require a post to have an image, then have a separate checkbox that says "delete exsisting image"? If the user checks it, then set the post_image to an empty string and remove the image file as well. If this checkbox is unchecked, but the post_image control was left empty, then do not set post_image field in the db to empty string.
Thanks to #shadow I figured it out. I changed the condition for the update query. This is my solution:
if($post_image!= null AND isset($_FILES['post_image'])){
$sql = "UPDATE posts SET post_template=?, post_title=?, post_content=?, post_tags=?, post_image=?, post_cat_id=?, post_video_url=? WHERE post_id=?";
$query = $db->prepare($sql);
$query->execute(array($post_template,$post_title,$post_content,$post_tags,$post_image,$post_cat_id,$post_video_url,$post_id));
}
else {
$sql = "UPDATE posts SET post_template=?, post_title=?, post_content=?, post_tags=?, post_cat_id=?, post_video_url=? WHERE post_id=?";
$query = $db->prepare($sql);
$query->execute(array($post_template,$post_title,$post_content,$post_tags,$post_cat_id,$post_video_url,$post_id));
}
Related
On my website, I have a form which allows the user to modify a selected item. As a part of this modification, they are allowed the upload (or delete) images associated with the item.
It seems that very specific images are causing my form to not post (I make this assumption because the loading indicator for my browser is pending).
From further inspection, although it does create a file, it's size is 0B. This is concurrent with the fact that the output of $_FILE['tree-photos']['size'][0] is 0. It seems that the image isn't even being attempted to be uploaded as a specific error code is not given by $_FILE['tree-photos']['error'][0] (returns 0).
I have changed all the appropriate file permissions required and the upload_max_size and post_max_size values accordingly. Interestingly, other files from the same folder which follow the exact same naming scheme and are larger upload fine. It seems random which photos trigger the form to not submit, but it is consistent what images do and don't submit.
File extensions are not the problem either, they are consistient.
Here is my code (I have been told off before for not posting all my code so sorry if a lot of it is not required):
<?php
include("../content/head.php");
include("../functions.php");
if (!isset($_SESSION['admin'])) {
header("Location: ../admin/admin.php?page=login");
exit();
}
$id = $_REQUEST['treeID'];
$tree_sql = "SELECT * FROM trees WHERE treeID=" . $id;
$tree_query = mysqli_query($dbconnect, $tree_sql);
$tree_rs = mysqli_fetch_assoc($tree_query);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$com_name = test_input($_POST['com_name']);
$sci_name = test_input($_POST['sci_name']);
$height = test_input($_POST['height']);
$origin = test_input($_POST['origin']);
$description = test_input($_POST['description']);
$type = test_input($_POST['type']);
if(isset($_FILES['tree-photos']['name'][0])) {
if (!empty($_FILES['tree-photos']['name'][0])) {
for ($i = 0; $i < count($_FILES['tree-photos']['name']); $i++) {
$location = '../images/' . $sci_name .'/' . $sci_name . "_" . uniqid() . "." . strtolower(pathinfo($_FILES['tree-photos']['name'][$i], PATHINFO_EXTENSION));
move_uploaded_file($_FILES['tree-photos']['tmp_name'][$i], $location);
}
}
}
if ($tree_rs["photo"] == "noimage") {
$updatesql = "UPDATE trees SET photo='$sci_name' WHERE treeID=".$id;
}
$_SESSION['err'] = $_FILES['tree-photos']['error'][0];
$updatesql = "UPDATE trees SET com_name='$com_name', sci_name='$sci_name', height='$height', origin='$origin', description='$description', type='$type' WHERE treeID=".$id;
$updatequery = mysqli_query($dbconnect, $updatesql);
}
$tree_sql = "SELECT * FROM trees WHERE treeID=" . $id;
$tree_query = mysqli_query($dbconnect, $tree_sql);
$tree_rs = mysqli_fetch_assoc($tree_query);
include("../content/navigation.php");
?>
<div id="main-container">
Back
<h1><?php echo $_SESSION['err']; ?></h1>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])."?treeID=".$id;?>" method="post" enctype="multipart/form-data">
<p>Common Name</p>
<input name="com_name" type="text" value="<?php echo $tree_rs['com_name']; ?>">
<p>Scientific Name</p>
<input name="sci_name" type="text" value="<?php echo $tree_rs['sci_name']; ?>">
<p>Height Name</p>
<input name="height" type="number" value="<?php echo $tree_rs['height']; ?>">
<p>Origin</p>
<input name="origin" type="text" value="<?php echo $tree_rs['origin']; ?>">
<p>Type</p>
<select name="type">
<option value="Deciduous">Deciduous</option>
<option value="Evergreen">Evergreen</option>
</select>
<p>Description</p>
<textarea name="description"><?php echo $tree_rs['description']; ?></textarea>
<p>Add Photos</p>
<input name="tree-photos[]" type="file" multiple>
<?php $tree_rs['photo']; ?>
<?php
if ($tree_rs['photo'] != "noimage") { ?>
<div class="edit-images-container"> <?php
$path = "../images/".$tree_rs['photo']."/";
$images = glob("$path*.{jpg,jpeg,png,gif,bmp}", GLOB_BRACE);
foreach($images as $image) { ?>
<div class="image-editable-container">
<img class="editable-image" data-source="<?php echo $tree_rs['sci_name']; ?>" data-id="<?php echo $tree_rs["treeID"]; ?>" src="<?php echo $image?>" alt="<?php echo $tree_rs['com_name'] . " - " . $tree_rs['description']; ?>">
<img class="editable-image-delete" src="../images/delete.svg" alt="Delete Button">
</div>
<?php } ?> </div> <?php
} else { ?>
<p>No Images Currently</p>
<?php }
?>
<input type="submit" value="Submit">
</form>
</div>
<?php include("../content/footer.php"); ?
Edit: Included some images that work and don't work for me, would be interesting if its the same for you.
Edit 2: It seems that after restarting the server I am able to upload around 15 items, including ones I couldn't before. After that, though new random images are un-uploadable. This might be a config issue.
<?php
include('../connect.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM discharge WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
echo '<img src=../'.$row['ppic'].' style="float:left; margin-right:10px;">';
echo '<img src=../'.$row['ppic1'].' style="float:left; margin-right:10px;">';
}
?>
<form action="editpicexec.php" method="post" enctype="multipart/form-data">
<br>
<input type="hidden" name="roomid" value="<?php echo $_GET['id']; ?>">
Select Image
<br>
<input type="file" name="image[]" multiple="multiple" /><br>
<input type="file" name="image1"><br>
<input type="submit" value="Upload">
</form>
discharge is my table database, I want to add picture multiple at in one input.
in this code I am opening a file one at a time, but I want to add multiple picture and then save in the field on the database
<?php
include('../connect.php');
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}else
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
$image_size= getimagesize($_FILES['image']['tmp_name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"../images/" . $_FILES["image"]["name"]);
$location="images/" . $_FILES["image"]["name"];
$roomid=$_POST['roomid'];
if(!$update=mysql_query("UPDATE discharge SET ppic = '$location' WHERE id='$roomid'"))
if (!isset($_FILES['image1']['tmp_name'])) {
echo "";
}else
$file=$_FILES['image1']['tmp_name'];
$image1= addslashes(file_get_contents($_FILES['image1']['tmp_name']));
$image1_name= addslashes($_FILES['image1']['name']);
$image1_size= getimagesize($_FILES['image1']['tmp_name']);
move_uploaded_file($_FILES["image1"]["tmp_name"],"../images/" . $_FILES["image1"]["name"]);
$location="images/" . $_FILES["image1"]["name"];
$roomid=$_POST['roomid'];
if(!$update=mysql_query("UPDATE discharge SET ppic1 = '$location' WHERE id='$roomid'"))
?>
Then this is my process I dont know how can I upload on database in single input with many pictures . ppic and ppic1 is the name of my field on my database.
if I understood your question right. You might want to use foreach to go through all file in image input like this:
foreach ($_FILES['image'] as $one_file){
$file=$one_file['tmp_name'];
// rest of code
// in the case you want to save all path in same field, change the line bellow like this
// if(!$update=mysql_query("UPDATE discharge SET ppic = concat(ppic, '$location' ) WHERE id='$roomid'"))
}
?>
Instead of concat(ppic, '$location' ) you can use CONCAT_WS(',', ppic, '$location') to separate it by comma.
This question already has answers here:
PHP form not uploading file
(2 answers)
Closed 7 years ago.
Update: I have uploaded images using PHP BLOB, but they are not showing up in mysql table. Images are being moved to the destination folder but are not showing up in table. and when I fetch the images this code nothing shows up
Code for uploading images
<?php
if (isset($_POST['add_p'])) {
#$pn = $_POST['pname'];
#$pp = $_POST['pprice'];
#$pc = $_POST['pcategory'];
#$date = date('d-m-y H:i:s');
$img = $_FILES['img']['name'];
$tmp_img = $_FILES['img']['tmp_name'];
move_uploaded_file($tmp_img, "uploads/$img");
$insert = "INSERT INTO products (`p_name`, `p_price`, `img`, `p_category`, `date_added`) VALUES ('$pn', '$pp', '$img', '$pc', '$date')";
mysqli_query($con, $insert);
}
?>
<form action="add-product.php" method="POST" class="form">
Name: <input class="inpt" type="text" name="pname">
Price: <input class="inpt" type="text" name="pprice">
Upload Image: <input class="inpt" type="file" name="img">
Select Category
<select class="inpt" name="pcategory">
<option>Men</option>
<option>Women</option>
<option>Kids</option>
</select>
<input type="submit" name="add_p" value="Add Product">
</form>
Code for fetching images
<?php
$get = "SELECT * FROM products ORDER BY p_id DESC LIMIT 0,4";
$query = mysqli_query($con, $get);
while ($row = mysqli_fetch_array($query)) {
echo $id = $row['p_id'];
echo $n = $row['p_name'];
echo $p = $row['p_price'];
echo $c = $row['p_category'];
echo $i = $row['img'];
}
?>
Add enctype='multipart/form-data' to your form to support file uploads:
<form action="add-product.php" method="POST" class="form" enctype="multipart/form-data">
See this answer for more details on encoding types for HTML forms.
Can anyone help me with this, i have checked the SQL table names multiple times but every time i attempt to post it gives me an error. Pretty new to this. Thanks in advance.
require_once('connect.php');
if (isset($_POST['add_product'])):
$product_description=$_POST['product_description'];
$price=$_POST['price'];
$reorder_level=$_POST['reorder_level'];
$current_level=$_POST['current_level'];
$imagename = $_FILES['image']['name'];
$add_this = "products/$imagename";
move_uploaded_file($_FILES['image']['tmp_name'],$add_this);
$my_query="INSERT INTO products VALUES ('','$product_description','$price','$reorder_level','$current_level', '$imagename')";
$result= mysqli_query($connection, $my_query);
if ($result):
echo "<b>Item Successfully Added!</b>";
echo "File ";
echo $_FILES['image']['name'];
echo " was uploaded - ";
echo $_FILES['image']['size'];
echo " bytes in size<br>Temporary name: ";
echo $_FILES['image']['tmp_name'];
echo " - file type: ";
echo $_FILES['image']['type'];
else:
echo "<b>ERROR: unable to post.</b>";
endif;
endif;
require_once 'header1.php';
?>
Here is the form im using
<H1>Add a New Product</H1>
<table>
<form method=post action="addproduct.php" enctype="multipart/form-data">
<tr><td><b>Product Description:</b><td><input type="text" name="product_description" size="30">
<tr><td><b>Price:</b><td><input type="text" name="price">
<tr><td><b>Re Order Level:</b><td><input type="text" name="reorder_level">
<tr><td><b>Stock Level:</b><td><input type="text" name="current_level">
<tr><td><b>Add Image:</b><td><input type="file" name="image">
<tr><td><input type="submit" name="add_product" >
</form>
</table>
</body>
<?php
require_once('connect.php');
$mysql = new MYSQLI("host", "username", "password", "database");
if (isset($_POST['add_product'])):
$product_description = $_POST['product_description'];
$price = $_POST['price'];
$reorder_level = $_POST['reorder_level'];
$current_level = $_POST['current_level'];
$imagename = $_FILES['image']['name'];
$add_this = "products/$imagename";
move_uploaded_file($_FILES['image']['tmp_name'],$add_this);
$mysql->query("INSERT INTO products (`NAME OF CELL IN TABLE WHERE YOU WANT SAVE0 $product_description`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $price`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $reorder_level`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $current_level`, `NAME OF CELL IN TABLE WHERE YOU WANT SAVE $imagename`) VALUES ('{$product_description}', '{$price}', '{reorder_level}', '{$current_level}', '{$imagename}')");
if ($result) {
echo "<b>Item Successfully Added!</b>";
echo "File ";
echo $_FILES['image']['name'];
echo " was uploaded - ";
echo $_FILES['image']['size'];
echo " bytes in size<br>Temporary name: ";
echo $_FILES['image']['tmp_name'];
echo " - file type: ";
echo $_FILES['image']['type'];
}
else {
echo "<b>ERROR: unable to post.</b>";
}
require_once('header1.php');
?>
Try this, but set your information on line 3 ($mysql)
and on line 15 ($mysql->query).
As a school assignment I need to make a cms, in that I need to be able to make post edit them and delete them. so for i can edit and delete them, but for some reason I cant get it to insert the post(and also the categories, same almost the same) I hope you guys can help me.
Here is the code:
The form
<form action="includes/doAddpost.php" method="post">
<label for="PostName">Name</label>
<input type="text" name="PostName" id="PostName" placeholder="Title" autofocus="auto"/>
<label for="PostAuthor">Author</label>
<input type="text" name="PostAuthor" id="PostAuthor" placeholder="Authors name"
value="<?php if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
}
?>"/>
<label for="PostContent">Content</label>
<textarea name="PostContent" id="PostContent" placeholder="content"></textarea>
<label for="PostCats">category</label>
<select name="PostCats">
<?php
$query = "SELECT * FROM categories";
$result = mysqli_query($mysqli, $query);
while ($cat = mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $cat['id']; ?>"><<?php echo $cat['title']; ?></option>
<?php } ?>
and this part doesnt seem to work either
</select>
<input type="submit" name="submit" value="submit"/>
</form>
Here is the doAddpost page:
<?php
include '../../includes/functions.php';
sec_session_start();
if(isset($_POST['submit'])){
if(isset($_POST['PostName'])){
if(isset($_POST['PostContent'])){
addPost($mysqli,$_POST['PostName'],$_POST['PostAuthor'], $_POST['PostContent'],$_POST['PostCats']);
header("Location: ../posts.php");
}else{
echo"please enter some content!";
}
} else{
echo"please set a category name!";
include('../addpost.php');
}
}else{
header("Location: ../addpost.php");
}
?>
and the function:
function addPost($mysqli, $pName, $pAuthor, $pContent, $pCat = 1)
{
$query = "INSERT INTO posts VALUES ('$pName', '$pAuthor', '$pContent', $pCat)";
mysqli_query($mysqli, $query);
}
Can anyone tell me what is the issue I am facing ?
Just edit your function as ,
function addPost($mysqli, $pName, $pAuthor, $pContent, $pCat = 1)
{
$query = "INSERT INTO posts (`your_column1`, `your_column_2`, `your_column_3`, `your_column_4`) VALUES ('$pName', '$pAuthor', '$pContent', $pCat)";
mysqli_query($mysqli, $query) or die(mysqli_error());
}
and then try...
Also in you select list change it as,
<option value="<?php echo $cat['id']; ?>"><?php echo $cat['title']; ?></option>
You placed an extra < there in your code..check that...:)
Now its time to step by step debugging:-
1) change your select category mysqli_query as below for debugging purpose
mysqli_query( $mysqli , $query ) or trigger_error($mysqli->error."($query)");
2) for you insert query mention column name in which you want to insert record . as you mentioned in comment you dont want id null so you should make you id column as AUTOINCREMENT
e.g
INSERT INTO posts (`column1`,`column2`,`column3`,`column4`) VALUES ('$pName', '$pAuthor', '$pContent', $pCat);