Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

PHP Problem with uploading an image to MySQL Database

JimmysNetwork

Legendary Coder
Hi all,

My goal: I am trying to have a system where users can upload an image, and it will save into ../assets/uploads & my image area in the database (
image varchar(255) latin1_swedish_ci Yes NULL ). I have also gave permissions for the files to be uploaded into the correct directory, and it is pulling images from there currently.

My problem: I can manually add an image to the database, and attach it to the users website in the table. I cannot however update the image when I try to do so in my edit module. I can provide the code below, maybe you can see something I am missing. I am getting the following error:

[B]Fatal error[/B]: Uncaught Error: Call to a member function execute() on string in public_html/domain.com/dev/user/dashboard.php:108 Stack trace: #0 {main} thrown in [B]public_html/domain.com/dev/user/dashboard.php[/B] on line 108

PHP logic for the edit module:


PHP:
if (isset($_POST['edit_website'])) {
        $id = $_POST['website_id'];
        $name = trim($_POST['name']);
        $url = trim($_POST['url']);
        $description = trim($_POST['description']);
        
        // Handle image upload
        $image = $_FILES['image']['name'];
        $image_temp = $_FILES['image']['tmp_name'];
        $image_error = $_FILES['image']['error'];
        
        // Check if an image was uploaded
        if ($image_error === 0) {
            // Define the image upload directory
            $upload_dir = '../assets/uploads';  // Ensure this directory exists and is writable
            $image_path = $upload_dir . basename($image);
            
            // Move the uploaded image to the specified directory
            if (move_uploaded_file($image_temp, $image_path)) {
                // Success
                $image = basename($image);  // Get the image filename (for database storage)
            } else {
                // Error uploading the image
                $error = 'Error uploading the image. Please try again.';
            }
        } else {
            // If no image was uploaded, keep the old image value
            $image = null;
        }
        // Check if required fields are empty
        if (empty($name) || empty($url) || empty($description)) {
            $error = 'All fields are required to edit the website.';
        } else {
            // Prepare the SQL query to update the website
            $query = "UPDATE websites SET name = :name, url = :url, description = :description";
            
            // Only update the image if a new one is uploaded
            if ($image) {
                $query .= ", image = :image";
            }
            
            $query .= " WHERE id = :id AND user_id = :user_id";
    
            $stmt = $pdo->prepare($query);
    
            // Bind the parameters
            $params = [
                'name' => $name,
                'url' => $url,
                'description' => $description,
                'id' => $id,
                'user_id' => $user_id,
            ];
    
            // Add the image parameter only if an image is provided
            if ($image) {
                $params['image'] = $image;
            }
    
            // Execute the statement
            $stmt->execute($params);
    
            // Success message
            $success = 'Website updated successfully!';
        }
    }

HTML Code:
HTML:
<div class="modal fade" id="editWebsiteModal<?= $website['id'] ?>" tabindex="-1" aria-labelledby="editWebsiteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="dashboard.php" enctype="multipart/form-data">
                <div class="modal-header">
                    <h5 class="modal-title" id="editWebsiteModalLabel">Edit Website</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="website_id" value="<?= $website['id'] ?>">

                    <!-- Website Name -->
                    <div class="mb-3">
                        <label for="name" class="form-label">Name</label>
                        <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($website['name']) ?>" required>
                    </div>

                    <!-- Website URL -->
                    <div class="mb-3">
                        <label for="url" class="form-label">URL</label>
                        <input type="url" name="url" class="form-control" value="<?= htmlspecialchars($website['url']) ?>" required>
                    </div>

                    <!-- Website Description -->
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="3" required><?= htmlspecialchars($website['description']) ?></textarea>
                    </div>

                    <!-- Image Upload (optional) -->
                    <div class="mb-3">
                        <label for="image" class="form-label">Image</label>
                        <input type="file" name="image" class="form-control">
                        <small class="text-muted">Leave empty to keep the current image.</small>
                    </div>

                    <!-- Current Image Display (optional) -->
                    <?php if (!empty($website['image'])): ?>
                        <div class="mb-3">
                            <label class="form-label">Current Image</label>
                            <div>
                            <?php if (!empty($website['image'])): ?>
                            <img src="assets/uploads/<?= htmlspecialchars($website['image']) ?>" alt="<?= htmlspecialchars($website['name']) ?>" class="img-fluid mb-3">
                        <?php endif; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                </div>
                <div class="modal-footer">
                    <button type="submit" name="edit_website" class="btn btn-primary">Save Changes</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
    </div>
</div>

Thank you in advance for any assistance.
 
You are not showing all your code or you forgot to define $pdo. X E.

My PDO is defined in the config.php file;


PHP:
<?php

// MySQL database info here

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}
?>
 
Maybe there is a log or something and if I recall correctly you have to make a table with a specific format to input that kind of data to, like raw or something, maybe max size is too small. It should only allow a few MB last time I knew about databases, you could save it as a file on your server though. Have you created a tablet yet and what is it like now? X E.
 
Maybe there is a log or something and if I recall correctly you have to make a table with a specific format to input that kind of data to, like raw or something, maybe max size is too small. It should only allow a few MB last time I knew about databases, you could save it as a file on your server though. Have you created a tablet yet and what is it like now? X E.

I have created a table and it will pull the image that is attached to that website. Basically the system stores the image like: ../assets/uploads/siteimg1.jpg & it will attach the file name to that site in database (example below):

1735426630607.webp

It will also display it correctly on the index page. So it is reading it correctly somewhere. I just can't update the image from the edit module.

1735426681882.webp

I hope this makes sense on what I am trying to explain.
 
Well, is it being saved to location and is it input to table? Probably not. Have you tried input directly to a query in PHP what string to run? Which line exactly is error at, execution of query right? X E.
 
Well, is it being saved to location and is it input to table? Probably not. Have you tried input directly to a query in PHP what string to run? Which line exactly is error at, execution of query right? X E.

I'm confused what you are referring to? The error is on line 108 which is:


PHP:
    // Refresh websites list after changes
    $query->execute(['user_id' => $user_id]);
    $websites = $query->fetchAll(PDO::FETCH_ASSOC);
}
 
I'm confused what you are referring to? The error is on line 108 which is:


PHP:
    // Refresh websites list after changes
    $query->execute(['user_id' => $user_id]);
    $websites = $query->fetchAll(PDO::FETCH_ASSOC);
}
I mean to build your query, use variables directly to make a string, not using options, if it is not going in then something is wrong with that, if it is going in then something is wrong somewhere else. X E.
 
Hi,

First let me state that I have not used PDO directly in a very long time so I am rusty.

I'm also not sure if all of the relevant code is present but I have not seen where you have something similar to this (from your code above) for the query that is dying on you.

As a general rule of thumb I would highly recommend using a good DBAL. It will make your life a lot less frustrating.
$query .= " WHERE id = :id AND user_id = :user_id";

$stmt = $pdo->prepare($query);
But, that is actually not the reason I decided to reply.

I have not seen where you are hashing your filenames during the upload process. If you do not hash them then you are possibly creating an attack vector by saving the file with a known filename. If they probe you with a valid file to check the path, then update the upload they could potentially upload a file with malicious content and execute it on the server.
 
Back
Top Bottom