0

Im trying to not show the remove button to the users that did not uploaded image to website, and I want the remove button be shown only for the user that uploaded a specific image. The problem is, it is in foreach loop, I tried with

if($user_id == $_GET['id'] 

but it show every button, but when I put

if($user_id != $_GET['id']) 

all button disappear.

This is the button I would like to show/hide

<?php

require('dbconfig.php');

if(!$user->is_loggedIn()) {
    $user->Redirect('index.php');
}

$user_id = $_SESSION['user_session'];

$stmt = $db_conn->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);

// print_r($userRow);


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

    $folder = "/Library/WebServer/Documents/Website/uploads/";
    $image = $_FILES['image']['name']; 
    $path = $folder . $image ; 
    $target_file=$folder.basename($_FILES["image"]["name"]);
    $imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
    $allowed=array('jpeg','png' ,'jpg'); $filename=$_FILES['image']['name']; 
    $ext=pathinfo($filename, PATHINFO_EXTENSION); 

    if(!in_array($ext,$allowed)) { 
        echo "Sorry, only JPG, JPEG, PNG & GIF  files are allowed.";
    } else {
        $success = "Image uploaded successfully";
        move_uploaded_file( $_FILES['image'] ['tmp_name'], $path);  
        
        $stmt = $db_conn->prepare("INSERT INTO images (img, user_id) VALUES (:image, :user_id)");
        $stmt->bindparam(":image",$image);
        $stmt->bindparam(":user_id",$user_id);
        $stmt->execute();
    } 
} 

$subjects = $db_conn->prepare("SELECT img FROM images");
$subjects->setFetchMode(PDO::FETCH_ASSOC);
$subjects->execute();

$stmt = $db_conn->prepare("SELECT user_id FROM images");
$stmt->execute();
$nesto=$stmt->fetchAll(PDO::FETCH_ASSOC);


echo '<pre>';
print_r($nesto);
echo '</pre>';

// echo $nesto['user_id'];

$ids = $_GET['id'];
?>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Jekyll v4.0.1">
    <title>Management</title>

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }
    </style>
    <!-- Custom styles for this template -->
    <link href="album.css" rel="stylesheet">
  </head>
  <body>
    <header>
        <div class="navbar navbar-dark bg-dark shadow-sm">
            <div class="container d-flex justify-content-between">
                <a href="#" class="navbar-brand d-flex align-items-center">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true" class="mr-2" viewBox="0 0 24 24" focusable="false"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>
                <strong>Pictures</strong>
                </a>
                <a href="#">Home</a>
                <a href="<?php echo 'profile.php?id=' . $user_id; ?>">Profile</a>
            </div>
        </div>
    </header>

<main role="main">
  <section class="jumbotron text-center">
    <div class="container">
      <h1>Shared Gallery</h1>
      <p class="lead text-muted"><?php print($userRow['user_name']); ?></p>
      <p>
      <p><?php echo $success; ?></p>
        <!-- Upload Image Form -->
        <div>
          <form method="POST" enctype="multipart/form-data"> 
            <input type="file" name="image" /> 
            <input type="submit" name="ok"/> 
          </form>
        </div>
        <!-- End Upload Image Form -->

        <a href="logout.php" name="logoutusr" class="btn btn-primary my-2">Logout</a>
      </p>
    </div>
  </section>

  <div class="album py-5 bg-light">
    <div class="container">

      <div class="row">

        <!-- START -->
        <?php foreach($subjects as $subject) { ?>
        <div class="col-md-4">
          <div class="card mb-4 shadow-sm">
            <img src="uploads/<?php echo $subject['img']; ?>" class="bd-placeholder-img card-img-top" width="100%" height="225" focusable="false"/>
            <div class="card-body">
              <p class="card-text">
                  <ul>
                      <li>Username</li>
                      <li>Email</li>
                      <li>Address</li>
                  </ul>
              </p>
              <div class="d-flex justify-content-between align-items-center">
                <div class="btn-group">

               THIS IS THE BUTTON I WANT TO SHOW AND HIDE
                    <button type="button" class="btn btn-sm btn-outline-secondary">Remove</button>
               THIS IS THE BUTTON I WANT TO SHOW AND HIDE
                </div>
                <small class="text-muted">9 mins</small>
              </div>
            </div>
          </div>
        </div>
        <?php } ?>
        <!-- END -->
                      
      </div>
    </div>
  </div>

</main>

<footer class="text-muted">
  <div class="container">
    <p class="float-right">
      <a href="#">Back to top</a>
      <a href="<?php echo 'index.php' ?>">Back to index</a>
    </p>
  </div>
</footer>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
      <script>window.jQuery || document.write('<script src="/docs/4.5/assets/js/vendor/jquery.slim.min.js"><\/script>')</script><script src="/docs/4.5/dist/js/bootstrap.bundle.min.js" integrity="sha384-1CmrxMRARb6aLqgBO7yyAxTOQE2AKb9GfXnEo760AUcUmFx3ibVJJAzGytlQcNXd" crossorigin="anonymous"></script>

</body></html>
1
  • 1
    Small Point There is little point preparing a query like SELECT img FROM images with no parameters that need values bound to them. It is simpler to just use ->query() Commented Jul 22, 2020 at 9:52

2 Answers 2

1

If you change these 2 queries into one query, you would have a resultset with the img and the users id, you can then use that to compare with the user that is logged in

//$subjects = $db_conn->prepare("SELECT img FROM images");
//$subjects->setFetchMode(PDO::FETCH_ASSOC);
//$subjects->execute();

//$stmt = $db_conn->prepare("SELECT user_id FROM images");
//$stmt->execute();
//$nesto=$stmt->fetchAll(PDO::FETCH_ASSOC);

Replace as

$result = $db_conn->query("SELECT img, user_id FROM images");
$subjects = $result->fetchAll(PDO::FETCH_ASSOC);

Then around your button you can do

<?php
    // If this user uploaded this image they are allowed to remove it
    if ($subject->user_id == $_SESSION['user_session']) :    
        <button type="button" class="btn btn-sm btn-outline-secondary">Remove</button>
    endif;
?>

Big Note I dont see a session_start() in this code, as you are using $_SESSION you would need one of those right at the top of this script.

Sign up to request clarification or add additional context in comments.

3 Comments

This is very helpful, thanks ill try it right now, and my session_start is in the other file sry I didn't put the code here, its in the require('dbconfig.php'); at the top, it just includes connecting to the db and session start
RE: session_start() I rather expected it would be in there, but I had to mention it :)
yeah haha, good thinking, thanks again I battled with this for a few days but now you've made it simple
0

I decided to do it this way This worked for me perfectly.

    <!-- START -->
    <?php foreach($subjects as $subject) : ?>
    <div class="col-md-4">
      <div class="card mb-4 shadow-sm">
        <img src="uploads/<?php echo $subject['img']; ?>" class="bd-placeholder-img card-img-top" width="100%" height="225" focusable="false"/>
        <div class="card-body">
          <p class="card-text">
         
              <ul>
                  <li><?php echo $subject['img_id']; ?></li>
                  <li><?php echo $subject['user_name']; ?></li>
                  <li><?php echo $subject['user_email']; ?></li>
                  <li>Address</li>
              </ul>
         
          </p>
          <div class="d-flex justify-content-between align-items-center">
            <div class="btn-group">
          <?php foreach($subject as $val) : ?>
           <?php if ($user_id == $_SESSION['user_session'] && $val == $user_id) : ?>
            <?php $id = $subject['img_id']; ?>
            <form method="POST" action="<?php echo "delete.php?id=" . $subject['img_id']?>">
                <!-- <button name="remove" type="button" class="btn btn-sm btn-outline-secondary">Remove</button> -->
                <input type="hidden" name="del" value="1" />
            
                <input type="submit" name="del"  class="btn btn-sm btn-outline-secondary" value="Remove" />

           </form>
           <?php endif; ?>
           <?php endforeach; ?>
            </div>
          </div>
        </div>
      </div>
    </div>
           <?php endforeach; ?>
    <!-- END -->

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.