Get Gallery With Id

im creating simple blog site, in creating new page, i have insert image gallery too. page and gallery both have two different table as i couldn’t figure out how to insert gallery into single table (means gallery section in pages table, so i created two tables)

What im trying to achieve in update pages is that check if image is insert or not in update page. if image is insert then display image else allow user to upload image in update page

table_name = english_version (table for page)

id title Content

table_name = english_gallery (table for gallery)

gallery_id image_id image

*Where image_id = id (id from english_version)

so when user creates new page and sumbit, it is send to update page:
header(“Location:./update.php?update=$lastenterid”);
die();

so, if user forget to insert image for gallery then i want to give option for image upload in update pages…

if(isset($_GET['update'])){
    $update_id = intval($_GET['update']);
   
    $update = $conn->query("SELECT * FROM english_version WHERE id = $update_id ");
    while($rows = $update->fetch(PDO::FETCH_OBJ) ):
        $id = $rows->id;
        $title = $rows->title;
        $content = $rows->content;
    endwhile;
}

checking if image is insert or not

<form action="" method="post">
    <!-- english-version -->
    <input type="hidden" name="id" value="<?php echo $id;?>">
    
    <div class="form-group">
        <input type="text" name="title" class="form-control mt-3" value="<?php echo $title?>">
    </div>

    <div class="form-group">
        <textarea class="form-control" name="content" id="" cols="30" rows="10"><?php echo $content;?></textarea>
    </div>
    <div class="form-group">
            <?php 
//getting data from english_gallery (table for gallery)
            $gallery = $conn->query("SELECT * FROM english_gallery WHERE image_id = $update_id");
            while($rows_gal = $gallery->fetch(PDO::FETCH_OBJ) ):
                $id = $rows_gal->gallery_id;
                $image_id = $rows_gal->image_id;
                $image = $rows_gal->image;

                //check if image_id == $update_id (where $update is id of (primary_key) english_version (table for page))
                if($image_id == $update_id ){ ?>
                    <div class="image-gallery">
                        <img src="<?php echo $image;?>" alt="">
                    </div>
		            <?php        
		                }else{
		                    $targetDir = "image/";
		                    $allowTypes = array('jpg','png','jpeg','gif');
		                    
		                    $images_arr = array();
		                    foreach($_FILES['images']['name'] as $key=>$val){
		                        $image_name = $_FILES['images']['name'][$key];
		                        $tmp_name 	= $_FILES['images']['tmp_name'][$key];
		                        $size 		= $_FILES['images']['size'][$key];
		                        $type 		= $_FILES['images']['type'][$key];
		                        $error 		= $_FILES['images']['error'][$key];
		                        
		                        // File upload path
		                        $fileName = basename($_FILES['images']['name'][$key]);
		                        $targetFilePath = $targetDir . $fileName;
		                        
		                        // Check whether file type is valid
		                        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
		                        if(in_array($fileType, $allowTypes)){	
		                            // Store images on the server
		                            if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$targetFilePath)){
		                                $images_arr[] = $targetFilePath;
		                                
		                                $insert = $conn->query("INSERT into english_gallery (image_id,image) VALUES ('$update_id','$targetFilePath')");

		                                $galleryid = $conn->lastInsertId();

		                                if($insert){
		                                    $count = $key + 1;
		                                    $statusMsg = " ".$count. " image file has been uploaded successfully.";
		                                }else{
		                                    $statusMsg = "Failed to upload image";
		                                } 
		                                
		                            }else{
		                                $statusMsg = "Sorry, there was an error uploading your file.";
		                            }
		                        }else{
		                            $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
		                        }
		                    }//multiple_image upload starts
		            ?>        
		          <!-- if image_id !== $update then display multi-image upload section --> 
	              	<div class="form-group">
	                    <input type="file" name="images[]" multiple>
	                </div> 
	            <?php
	                }

	                endwhile;  
	            ?>
    </div>

    <div class="form-group">
       <input type="submit" value="Update" name="update" class="btn btn-primary">
    </div>  
    <!-- english-version -->
</form>

if($image_id == $update_id ){

if there is image its displaying image but if there no image its not displaying input option for image upload

rr

if think else conditions is not working because $image_id stores id of (primary_key) english_version (table for page)) it’s checking for the id which is never created…

so, how can i get the condition, where if user have insert image then image will displayed else user will get option for image uploading…

If there are no rows WHERE image_id = $update_id, your whole while will never occur, so you never get to your if…else.

You need to check the number of rows returned by your query first. That is your “if”. (You could do this by changing the while to an if, if there will only ever be 1 image per page; that said, if there would only be one, you should be able to merge the tables.)

joining both tables.

if(isset($_GET['update'])){
    $update_id = intval($_GET['update']);
   	//combining two tables
    $data = $conn->query("SELECT v.id, v.parent_id, v.title, v.content, g.image FROM english_version v LEFT JOIN english_gallery g ON $update_id = g.gallery_id ORDER BY v.id");
    while($rows15 = $data->fetch(PDO::FETCH_OBJ) ):
        $id = $rows15->id;
        $drop_id = $rows15->parent_id;
        $title = $rows15->title;
        $content = $rows15->content;
        $image = $rows15->image;
    endwhile;

displaying value in form. so here im checking if image value is null then display upload option and if it has value display image, its working fine.

<div class="form-group">
    <?php 
    if($image == null){
    ?>        
      <div class="form-group">
            <input type="file" name="images[]" multiple>
      </div> 
    <?php
        }else{

            $gallery = $conn->query("SELECT * FROM english_gallery WHERE gallery_id = $update_id");
    		while($rows14 = $gallery->fetch(PDO::FETCH_OBJ) ):
		        $id = $rows14->gid;
		        echo $gallery_id = $rows14->gallery_id;
		        $gallery_image = $rows14->image;
		        $caption = $rows14->caption;
     ?>       
        	<div class="image-gallery">
                <img src="<?php echo $gallery_image;?>" alt="">
                <input type="text" value="<?php echo $caption; ?>">
            </div>
     <?php       
        endwhile; }

        }
    ?>
</div>  

Now im trying to insert image if value is empty.

if(isset($_POST['update'])){
	$targetDir = "gallery/";
        $allowTypes = array('jpg','png','jpeg','gif');
        
        $images_arr = array();
        foreach($_FILES['images']['name'] as $key=>$val){
            $image_name = $_FILES['images']['name'][$key];
            $tmp_name   = $_FILES['images']['tmp_name'][$key];
            $size       = $_FILES['images']['size'][$key];
            $type       = $_FILES['images']['type'][$key];
            $error      = $_FILES['images']['error'][$key];
            
            // File upload path
            $fileName = basename($_FILES['images']['name'][$key]);
            $targetFilePath = $targetDir . $fileName;
            
            // Check whether file type is valid
            $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
            if(in_array($fileType, $allowTypes)){   
                // Store images on the server
                if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$targetFilePath)){
                    $images_arr[] = $targetFilePath;
                    
                    $insert = $conn->query("INSERT into english_gallery (gallery_id,image,caption) VALUES ('$id','$targetFilePath','$targetFilePath')");

                    $galleryid = $conn->lastInsertId();

                    if($insert){
                        $count = $key + 1;
                        $statusMsg = " ".$count. " image file has been uploaded successfully.";
                    }else{
                        $statusMsg = "Failed to upload image";
                    } 
                    
                }else{
                    $statusMsg = "Sorry, there was an error uploading your file.";
                }
            }else{
                $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
            }
        }//multiple_image upload starts
}

But when i press submit button its gives following error.

Notice: Undefined index: images

Notice: Trying to access array offset on value of type null

Warning: Invalid argument supplied for foreach() in

Why im not able to insert image from update page…

solve the above error forgot to put enctype=“multipart/form-data” in form but its inserting in same id what id i try to update, it’s insertingin id= 8

while joining tales english_version and english_gallery its query is pulling data from last insert id from english_version table while it should pull data from ‘url’ get method.

$data = $conn->query("SELECT v.id, v.parent_id, v.title, v.content, g.image FROM english_version v LEFT JOIN english_gallery g ON $update_id = g.gallery_id ");

this query is pulling that from last insert id. if i use single table data is fine

$data = $conn->query("SELECT * FROM english_version WHERE id = $update_id ");

but with single table, i can’t check for empty image values…

why this query is giving me last insert id, instead of pulling that from url

$data = $conn->query("SELECT v.id, v.parent_id, v.title, v.content, g.image FROM english_version v LEFT JOIN english_gallery g ON $update_id = g.gallery_id ");

Don’t put external, unknown, dynamic values directly into an sql query statement. Use a prepared query.

The ON … term in a join query defines the relationship to use between the tables being joined. You would need to use (probably) v.id = g.image_id To match data for a specific blog id, you would use WHERE v.id = ? (using a prepared query place-holder.)

1 Like

I have reviewed the information in this thread. You have some confusing naming and it appears that you don’t have a statement of what you are trying to accomplish, making it hard to write code/query(ies) that do what you want.

The main table is for blog posts? It should be named blog_posts_english or similar.

The columns you have listed and are using in the gallery/image table don’t match or make sense. This table can have zero or more rows per blog post. I recommend that this table have columns for - id or image_id if you prefer (autoincrement), blog_post_id, filename, and caption. The filename should not include the path so that you can organize your files anyway you want and you won’t need to modify the stored data to match. Just build the path/filename when you output the <img … tag.

For the update/edit operation, shouldn’t you -

  1. Display any existing images, with both a way to replace (select and upload a new image) or delete each one?
  2. Add new images?

This code has no user access security. By unconditionally using $_GET[‘update’] to specify the blog post id to edit, anyone can edit the data for any blog post. If you were doing this for real, you would have a user login and permission system. A logged in user would be required and that user could only see and do things he has permission to do. If blog posts are per user (you would need a user_id column in that table), the user can only edit their own blog posts.

The first version of this code has the post method form processing code inside the html document. It’s not clear where this is at in the last version of code, but based on some of the variables in it, it is probably still inside the html document. The code for any page should be laid out in this general order -

  1. Initialization.
  2. Post method form processing.
  3. Get method business logic - get/produce data needed to display the page.
  4. Html document.

If you organize your code this way, it will be easier to design, write, test, debug, and maintain the code, because the different responsibilities will be separated.

There’s actually a bunch of implantation problems with this code, the biggest one is that there is no error handling for the file uploads in the post method form processing. If the total size of the form data exceeds the post_max_size setting, both the $_POST and $_FILES arrays will be empty and this code won’t do anything. You should detect if a post method from was submitted, then test for this condition. If there is $_FILES data, you next need to test the [‘error’] element for each file to make sure that it actually uploaded without any error before trying to use any of the uploaded file information.

1 Like

I see that there is a caption for each image. When you loop to display the existing images, you would also output a form field with the existing captain, so that it can be edited/updated.

The section in the form for adding new images would also need a caption field for each image. Since you are using the multiple attribute, you can use javascript to get a count of the number of selected files, and output a caption field for each file.

WHERE v.id was helpful…

i have two table1st for page(content) and 2nd for gallery image, i have create table for gallery because i need multiple image, as i couldn’t store in english_version (table for content) so i create 2nd table for storing multiple image…english_gallery (table for gallery)

yes, you are right i need that feature… im still developing it…

im have login system only admin can edit it…

if(isset($_GET['update'])){

this will list data from database for particular id that we get from url with GET method

if(isset($_POST['update'])){

for updating data that user enters for updating…

code may be bit messy as im new and learning … thank for being Mentor and guiding. please make correction, where it need to be correct as im still learning so there may mistakes

yes, you are right i didnt get any error… while exceeding file size, so sir how can i correction this so that if file size is exceed user get warning message… how can display warning message for file size exceed

The rest of that paragraph stated what to do - You should detect if a post method from was submitted, then test for this condition. If there is $_FILES data, you next need to test the [‘error’] element for each file to make sure that it actually uploaded without any error before trying to use any of the uploaded file information.

There are actually several reasons why the $_FILES array can be empty -

  1. Uploads are not enabled on your server in the php.ini.
  2. The form tag does not contain - enctype=‘multipart/form-data’ or something else about the form markup makes it invalid.
  3. There is no type=‘file’ field in the form.
  4. The total size of the data from the form exceeds the post_max_size setting.

After you have eliminated the first three reasons, you can simply test for empty($_FILES).

The code to do that looks like -

$errors = []; // an array to hold user/validate errors

// post method form processing
if($_SERVER['REQUEST_METHOD'] == "POST")
{
	if(empty($_FILES))
	{
		$errors['images'] = 'The total size of the form data is too large.';
	}
	else
	{
		// the $_FILES processing code goes here
		// you need to test the ['error'] element of each file before using any of the file information
		// the error values can be found here - https://www.php.net/manual/en/features.file-upload.errors.php
	}
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.