Jump to content

Image code modification


Mekaboo
 Share

Recommended Posts

Hey☺️

Implemented a script and it works fine but want to tweak it so only one image is displayed after upload. As of now image is displayed after upload but also images previously uploaded (like a gallery). Goal is to have a singular profile image instead of a profile image gallery. Here is my code:

upload.php

```

<?php
// Include the database configuration file
require_once 'dbConfig.php';

// If file upload form is submitted
$status = $statusMsg = '';
if(isset($_POST["submit"])){
    $status = 'error';
    if(!empty($_FILES["image"]["name"])) {
        // Get file info
        $fileName = basename($_FILES["image"]["name"]);
        $fileType = pathinfo($fileName, PATHINFO_EXTENSION);
        
        // Allow certain file formats
        $allowTypes = array('jpg','png','jpeg','gif');
        if(in_array($fileType, $allowTypes)){
            $image = $_FILES['image']['tmp_name'];
            $imgContent = addslashes(file_get_contents($image));
        
            // Insert image content into database
            $insert = $db->query("INSERT into img (image, uploaded) VALUES ('$imgContent', NOW())");
            
            if($insert){
                $status = 'success';
                $statusMsg = "File uploaded successfully.";
            }else{
                $statusMsg = "File upload failed, please try again.";
            }
        }else{
            $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
        }
    }else{
        $statusMsg = 'Please select an image file to upload.';
    }
}

// Display status message
//echo $statusMsg;
?>

```

 

view.php

```

   
      <?php
// Include the database configuration file
require_once 'dbConfig.php';

// Get image data from database
$result = $db->query("SELECT image FROM img ORDER BY uploaded DESC");
?>
      <div class="container">
    <?php if($result->num_rows > 0){ ?>
        <div class="w3-container">
            <?php while($row = $result->fetch_assoc()){ ?>
                <img src="data:image/jpg;charset=utf8;base64,<?php echo base64_encode($row['image']); ?>" />
            <?php } ?>
        </div>
    <?php }else{ ?>
        <p class="status error">Image(s) not found...</p>
    <?php } ?>
</div>
     ```

 

Thank ya ❤️

 

 

Link to comment
Share on other sites

add LIMIT 1  

SELECT image FROM img ORDER BY uploaded DESC LIMIT 1

EDIT:

https://www.w3schools.com/php/php_mysql_select_limit.asp

NOTE: the row that gets selected depends on your whether your ORDER BY is ASC or DESC

Edited by niche
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...