We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Insert Image to Database With Field Type Blob Not Working in Phalcon

In Structure Table:

CREATE TABLE `m_product` ( 
    `product_id` VARCHAR(50) NOT NULL,
    `product_image` BLOB NOT NULL,
    PRIMARY KEY (`product_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB

In Volt:

<form action="Product/save" class="form-horizontal" role="form" name="FrmAddProduct" id="FrmAddProduct" method="post" autocomplete="off" enctype="multipart / form-data">
    <div class="section full mt-1 mb-2">
        <div class="section-title"><?php echo $text->_("lang85"); ?></div>
        <div class="wide-block pb-1 pt-1">
            <div class="custom-file-upload">
                <input type="file" id="fileuploadInput" name="fileuploadInput" accept=".png, .jpg, .jpeg">
                <label for="fileuploadInput">
                <span>
                    <strong>
                        <ion-icon name="cloud-upload-outline" role="img" class="md hydrated" aria-label="cloud upload outline"></ion-icon>
                        <i><?php echo $text->_("lang156"); ?></i>
                     </strong>
                </span>
            </label>
        </div>
        <div class="form-button-group">
            <button id="BtnAddProduct" type="submit" class="btn btn-primary btn-block btn-lg" ><?php echo $text->_("lang59"); ?></button>
        </div>
    </div>
</form>

In Controller :

public function saveAction()
{

    $check_id = "select product_id from m_product where 
    company_id='$company_id'";
    $sql_check=$this->db->query($check_id);     
    $row_check=$sql_check->fetchArray();
    $check_productid = $row_check["product_id"];
    if ( $check_productid == "" )
    {
        $product_id = $company_id . "0000000001";
    }else{
        $product_id_last = str_pad(intval(substr($check_productid, 5, 10)) + 1, 10, '0', STR_PAD_LEFT);
        $product_id = $company_id . $product_id_last;
    }

    $product = new MProduct();
    $product->product_id = $product_id;
    $product->product_image = base64_encode(file_get_contents($this->request->getUploadedFiles()[0]->getTempName()));

    if ($product->save()) {
        echo 1;
    }else{
        echo 0;
    }
}

Error :

<br />
<b>Fatal error</b>:  Uncaught Error: Access to undeclared static property: Phalcon\Di::$_default in C:\xampp\htdocs\oisi\app\config\services.php:21
Stack trace:
#0 [internal function]: Phalcon\Di-&gt;__construct()
#1 C:\xampp\htdocs\oisi\app\config\services.php(21): Phalcon\Di\FactoryDefault-&gt;__construct()
#2 C:\xampp\htdocs\oisi\public\index.php(22): include('C:\\xampp\\htdocs...')
#3 {main}

Next Error: Access to undeclared static property: Phalcon\Di::$_default in C:\xampp\htdocs\oisi\app\config\services.php:21
Stack trace:
#0 [internal function]: Phalcon\Di-&gt;__construct()
#1 C:\xampp\htdocs\oisi\app\config\services.php(21): Phalcon\Di\FactoryDefault-&gt;__construct()
#2 C:\xampp\htdocs\oisi\public\index.php(22): include('C:\\xampp\\htdocs...')
#3 {main}
thrown in <b>C:\xampp\htdocs\oisi\app\config\services.php</bon line <b>21</b><br />

In services :

<?php
/**
 * Services are globally registered in this file
 *
 * @var \Phalcon\Config $config
 */
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter;
use Phalcon\Session\Adapter\Files as SessionAdapter;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Session\Adapter\Files as Session;
use \Phalcon\Mvc\Dispatcher as PhDispatcher;
use Phalcon\Assets\Manager;

/**
 * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
 */
$di = new FactoryDefault();
/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->setShared('url', function () use ($config) {
    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);

    return $url;
});

/**
 * Setting up the view component
 */
$di->setShared('view', function () use ($config) {

    $view = new View();

    $view->setViewsDir($config->application->viewsDir);

    $view->registerEngines(array(
        '.volt' => function ($view, $di) use ($config) {

            $volt = new VoltEngine($view, $di);

            $volt->setOptions(array(
                'compiledPath' => $config->application->cacheDir,
                'compiledSeparator' => '_',
                'compileAlways' => true  
            ));

            return $volt;
        },
        '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
    ));

    return $view;
});

/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->setShared('db', function () use ($config) {
    $dbConfig = $config->database->toArray();
    $adapter = $dbConfig['adapter'];
    unset($dbConfig['adapter']);

    $class = 'Phalcon\Db\Adapter\Pdo\\' . $adapter;

    return new $class($dbConfig);
});

/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->setShared('modelsMetadata', function () {
    return new MetaDataAdapter();
});

/**
 * Register the session flash service with the Twitter Bootstrap classes
 */
$di->set('flash', function () {
    return new Flash(array(
        'error'   => 'alert alert-danger',
        'success' => 'alert alert-success',
        'notice'  => 'alert alert-info',
        'warning' => 'alert alert-warning'
    ));
});

/**
 * Start the session the first time some component request the session service
 */
$di->setShared('session', function () {
    //ini_set('session.gc_maxlifetime', 600);
    //session_set_cookie_params(600);
    $session = new SessionAdapter();
    $session->start();

    return $session;
});

$di->set(
    'dispatcher',
    function() use ($di) {

        $evManager = $di->getShared('eventsManager');

        $evManager->attach(
            "dispatch:beforeException",
            function($event, $dispatcher, $exception)
            {
                switch ($exception->getCode()) {
                    case PhDispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                    case PhDispatcher::EXCEPTION_ACTION_NOT_FOUND:
                        $dispatcher->forward(
                            array(
                                'controller' => 'Error',
                                'action'     => 'index',
                            )
                        );
                        return false;
                }
            }
        );
        $dispatcher = new PhDispatcher();
        $dispatcher->setEventsManager($evManager);
        return $dispatcher;
    },
    true
);

$di->setShared("assetsGlobal", function() {

      $assetManager = new Manager;
      $assetManager
          ->collection('header')
          ->addCss('assets/css/style.css',false)
          ->addCss('assets/css/font-awesome.min.css',false);

      $assetManager
          ->collection('footer')
          ->addJs('service-worker.js',false)
          ->addJs('assets/js/lib/jquery-3.4.1.min.js',false)
          ->addJs('assets/js/lib/popper.min.js',false)
          ->addJs('assets/js/lib/bootstrap.min.js',false)
          ->addJs('https://unpkg.com/[email protected]/dist/ionicons/ionicons.js',false)
          ->addJs('assets/js/plugins/owl-carousel/owl.carousel.min.js',false)
          ->addJs('assets/js/plugins/jquery-circle-progress/circle-progress.min.js',false)
          ->addJs('assets/js/jquery.mask.js',false);

      return $assetManager;

  });

  $di->setShared("assetsLocal", function() {

      $assetManager = new Manager;
      $assetManager->collection('header');
      $assetManager->collection('footer');

      return $assetManager;

  });

Please help me...

Can you please reformat your post using the preferred code method outlined here: https://forum.phalcon.io/help/markdown. Then it'll be easier to read your code.

Also, the error being thrown is from your config/services.php file - it would be helpful to post that too - or at least the service defined on line 21.

edited Dec '20

There is much debate about the best way to handle images in a system. Images related to the look of the site itself are best treated as assets and stored as files in the file system with other assets. Images which are uploaded by users, however, can reasonably be base64 encoded and stored as a Binary Large OBject in the database. This will incur a significant performance hit and will require the database to be able to grow to a much bigger size then it would with simple transactional data. The advantage of putting the image in the database is that it stores all data in one place and makes backup and data management much simpler. This can be a big advantage, particularly where organizations are subject to compliance issues in relation to how they store and manage user data. Many developers believe that as the system starts to scale that the optimum solution is to store the images on the file system and store the name of the image hashed in the database. This poses its own challenges. Some very large organizations use a combination of both - with caching of images used to Pupil Path improve performance but images ultimately stored in the database for backup and control purposes.

This series of posts will describe how to store an image in the database as a BLOB and then render that image. For this, we will use the tennisClub - extending the example to include images for members of the tennisClub.

Can you please reformat your post using the preferred code method outlined here: https://forum.phalcon.io/help/markdown. Then it'll be easier to read your code.

Also, the error being thrown is from your config/services.php file - it would be helpful to post that too - or at least the service defined on line 21.

Thank you for the advice, I have updated it, hope it can help me

There is much debate about the best way to handle images in a system. Images related to the look of the site itself are best treated as assets and stored as files in the file system with other assets. Images which are uploaded by users, however, can reasonably be base64 encoded and stored as a Binary Large OBject in the database. This will incur a significant performance hit and will require the database to be able to grow to a much bigger size then it would with simple transactional data. The advantage of putting the image in the database is that it stores all data in one place and makes backup and data management much simpler. This can be a big advantage, particularly where organizations are subject to compliance issues in relation to how they store and manage user data. Many developers believe that as the system starts to scale that the optimum solution is to store the images on the file system and store the name of the image hashed in the database. This poses its own challenges. Some very large organizations use a combination of both - with caching of images used to improve performance but images ultimately stored in the database for backup and control purposes.

This series of posts will describe how to store an image in the database as a BLOB and then render that image. For this, we will use the tennisClub - extending the example to include images for members of the tennisClub.

Thanks for the advice, I also thought that way, what is better to save it on the filesystem. The app I'm building will be accessible to everyone and allow them to save photos. but I am still new to phalcon regarding its data security