Search code examples
phpmysqldatabaseimagecodeigniter-4

image doesn't display from database Codeigniter 4


i am new using codigniter. i am trying to display images from the mysql database by sending them to the database using a create page where you can type in a title, some info and select an image, everything displays after creating a project except for the image. once i open phpmyadmin it shows that there is data for the image but it looks like it's only MetaData and not the actual image itself. i have been stuck on this for a couple of days now so i hope you guys could help me out!

create function in The Controller (edited):

    public function create(){
    $model = new ProjectModel();

    $file = $this->request->getFile('image');

    if ($this->request->getMethod() === 'post' && $this->validate([
            'title' => 'required|min_length[3]|max_length[255]',
            'info'  => 'required',
            'image' => 'uploaded[image]',
        ]))
    {
        $model->save([
            'title' => $this->request->getPost('title'),
            'slug'  => url_title($this->request->getPost('title'), '-', TRUE),
            'info'  => $this->request->getPost('info'),
            $tempfile = $file->getTempName(),
            $imgdata = file_get_contents($tempfile),
        ]);
        var_dump($imgdata);


        #echo view('project/success');
    }
    else
    {
        echo view('site/create');
    }
}

My Model

namespace App\Models;

use CodeIgniter\Model;

class ProjectModel extends Model
{
protected $table = 'projects';

protected $allowedFields = ['title', 'slug', 'info', 'image'];

public function getProjects($slug = false)
{
    if ($slug === false)
    {
        return $this->findAll();
    }

    return $this->asArray()
            ->where(['slug' => $slug])
            ->first();
}
}

this is the file that creates a div element once you press the create button

<?php if (! empty($projects) && is_array($projects)) : ?>

<?php foreach ($projects as $project_item): ?>

    <div class="project-box" href="/projects/<?= esc($project_item['slug'], 'url') ?>">

        <?php echo '<img class="project-image" src="data:image/jpeg;base64,'.base64_encode($project_item['image']).'" alt="image" ">'?>

            <p class="project-name"><?=esc($project_item['title'])?></p>
            <div class="bottom-border">
                <p class="project-creator"><i class="far fa-user-circle"></i>&nbsp;<?=esc($project_item['creator'])?></p>
                    <div class="statistics">
                        <p class="project-likes"><i class="fas fa-heart"></i>&nbsp;<?=esc($project_item['likes'])?></p>
                        <p class="project-views"><i class="far fa-eye"></i>&nbsp;<?=esc($project_item['views'])?></p>
                    </div>
            </div>
    </div>
   <?php endforeach; ?> 
<?php else : ?>
   <h3>No Projects</h3>
<?php endif ?>

this is the create file in which you can create a project

        <div class="parent">
           <?= \Config\Services::validation()->listErrors() ?>
            <form action="/site/create" method="post">
              <h1>Create Project</h1>
                <?= csrf_field() ?>
                <div class="form-group">
                    <input class="ph-title" type="input" name="title" placeholder="Title" /><br/>
                </div>
                <div class="grow-wrap">
                    <textarea class="ph-info" name="info" placeholder="Type in project info"></textarea>
                </div>

               <!-- <div class="file-input">
                    
                        <label for="file">
                            Select file
                            <p class="file-name"></p>
                        </label>
                </div> -->

                <input class="file-btn" type="file" name="image" value=""/><br/>
                <input class="create-btn" type="submit" name="submit" value="Create Project"/>
            </form>
    </div>

What am i doing wrong?


Solution

  • There are a few things wrong here. First off, your form is set for image uploading, but needs the enctype added to the form tag so that your backend PHP can recieve the $_FILES object

    <form action="/site/create" method="post" enctype="multipart/form-data">
    

    Remove the value="" from the input...

     <input class="file-btn" type="file" name="image" />
    

    Now you're ready to receive a file - see https://codeigniter4.github.io/userguide/libraries/uploaded_files.html

    Your validation should be altered

    $this->validate([
        //... your other validations...
        'image' => 'uploaded[image]' // instead of required
    ]);
    

    If you want to store the image on your server and then record the name of the image in the database to retrieve later:

    $imageDirectory="/path/to/where/you/store/images";
    $imageName = $file->getRandomName(); 
    $path = $this->request->getFile('image')->store($imageDirectory, $imageName);
    // path is now the full path to the image on your server.
    

    if you want to store the image BLOB data instead (like your example):

    $tempfile = $file->getTempName();
    $imgdata = file_get_contents($tempfile);
    

    Then your insert would look like this...

    $model->save([
                'title' => $this->request->getPost('title'),
                'slug'  => url_title($this->request->getPost('title'), '-', TRUE),
                'info'  => $this->request->getPost('info'),
                'image' => $imgdata,
            ]);