phpmysqlphalcon

Can't connect phalcon project with mysql database


I'm new into learning phalcon, I'm trying to setup a phalcon project, I've managed to serve it on my localhost and it kinda works except for when an interaction with the database is needed. I got a mysql user which I granted all privileges to and a database, which is actually connected to the project, because I have access to every table in my GUI. The problem is, when I try to submit a form and my database configs are set up correctly, the serves gives me 502 Bad Gateway response. However, when I mess up the user's password in the db config on purpose, the serves displays this error :

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)

#0 [internal function]: PDO->__construct()
#1 [internal function]: Phalcon\Db\Adapter\Pdo\AbstractPdo->connect()
#2 /var/www/simple-admin/app/config/services.php(131): Phalcon\Db\Adapter\Pdo\AbstractPdo->__construct()
#3 [internal function]: Closure->{closure}()
#4 [internal function]: Phalcon\Di\Service->resolve()
#5 [internal function]: Phalcon\Di->get()
#6 [internal function]: Phalcon\Di->getShared()
#7 /var/www/simple-admin/app/controllers/IndexController.php(81): Phalcon\Di\Injectable->__get()
#8 [internal function]: PSA\Controllers\IndexController->signupAction()
#9 [internal function]: Phalcon\Dispatcher\AbstractDispatcher->callActionMethod()
#10 [internal function]: Phalcon\Dispatcher\AbstractDispatcher->dispatch()
#11 /var/www/simple-admin/public/index.php(43): Phalcon\Mvc\Application->handle()
#12 {main}

When I try to test If I can get the values of a table from the database in the controller to check If I have access to it, like this :

public function indexAction()
    {
        $user = Users::where('id',1);
        var_dump($user);
    }

The server gives me the following error :

The method 'where' doesn't exist on model 'PSA\Models\Users'

#0 /var/www/simple-admin/app/controllers/IndexController.php(38): Phalcon\Mvc\Model::__callStatic()
#1 [internal function]: PSA\Controllers\IndexController->indexAction()
#2 [internal function]: Phalcon\Dispatcher\AbstractDispatcher->callActionMethod()
#3 [internal function]: Phalcon\Dispatcher\AbstractDispatcher->dispatch()
#4 /var/www/simple-admin/public/index.php(43): Phalcon\Mvc\Application->handle()
#5 {main}

This is the Users Model :

<?php
declare(strict_types=1);

namespace PSA\Models;

use Phalcon\Mvc\Model;
use Phalcon\Security;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
use PSA\Models\UsersRoles;

/**
 * All the users registered in the application
 */
class Users extends Model
{
    /**
     * @var integer
     */
    public $id;

    /**
     * @var string
     */
    public $name;

    /**
     * @var string
     */
    public $email;

    /**
     * @var string
     */
    public $password;

    /**
     * @var string
     */
    public $mustChangePassword;

    /**
     * @var string
     */
    public $banned;

    /**
     * @var string
     */
    public $suspended;

    /**
     * @var string
     */
    public $active;

    public function initialize()
    {
        // Audit
        $this->keepSnapshots(true);
        $this->addBehavior(new \PSA\Models\Blameable());

        $this->hasMany('id', UsersAuths::class, 'userID', [
            'alias' => 'usersAuths',
            'foreignKey' => [
                'message' => 'User cannot be deleted because he/she has activity in the system',
            ],
        ]);

        $this->hasMany('id', PasswordChanges::class, 'userID', [
            'alias' => 'passwordChanges',
            'foreignKey' => [
                'message' => 'User cannot be deleted because he/she has activity in the system',
            ],
        ]);

        $this->hasMany('id', ResetPasswords::class, 'userID', [
            'alias' => 'resetPasswords',
            'foreignKey' => [
                'message' => 'User cannot be deleted because he/she has activity in the system',
            ],
        ]);
    }

    /**
     * Before create the user assign a password
     */
    public function beforeValidationOnCreate()
    {
        if (empty($this->password)) {
            // Generate a plain temporary password
            $tempPassword = preg_replace('/[^a-zA-Z0-9]/', '', base64_encode(openssl_random_pseudo_bytes(12)));

            // The user must change its password in first login
            $this->mustChangePassword = 1;

            /** @var Security $security */
            $security = $this->getDI()->getShared('security');
            // Use this password as default
            $this->password = $security->hash($tempPassword);
        } else {
            // The user must not change its password in first login
            $this->mustChangePassword = 0;
        }

        // The account must be confirmed via e-mail
        // Only require this if emails are turned on in the config, otherwise account is automatically active
        if ($this->getDI()->get('config')->useMail) {
            $this->active = 0;
        } else {
            $this->active = 1;
        }

        // The account is not suspended by default
        $this->suspended = 0;

        // The account is not banned by default
        $this->banned = 0;
    }

    /**
     * Send a confirmation e-mail to the user if the account is not active
     */
    public function afterCreate()
    {
        // Only send the confirmation email if emails are turned on in the config
        if ($this->getDI()->get('config')->useMail && $this->active == 0) {
            $emailConfirmation = new EmailConfirmations();
            $emailConfirmation->userID = $this->id;

            if ($emailConfirmation->save()) {
                $this->getDI()
                    ->getFlash()
                    ->notice('A confirmation mail has been sent to ' . $this->email);
            }
        }
    }

    /**
     * Validate that emails are unique across users
     */
    public function validation()
    {
        $validator = new Validation();

        $validator->add('email', new Uniqueness([
            "message" => "The email is already registered",
        ]));

        return $this->validate($validator);
    }


    /**
     * get all roles
     */
    public function userRoles($userID)
    {
        return UsersRoles::find("userID = '$userID'");
    }

    /**
     * get all roleID
     */
    public function userRolesID($userID)
    {
        $result = [];
        $usersRoles = UsersRoles::find("userID = '$userID'");
        foreach ($usersRoles as $value) {
            $result[] = $value->roleID;
        }
        return $result;
    }

}

Config.php :

<?php

/*
 * Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line.
 * NOTE: please remove this comment.
 */

use Phalcon\Config;

defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');

return new Config([
    'database' => [
        'adapter' => 'mysql',
        'host' => 'localhost',
        'username' => 'root',
        'password' => 'Nikusha_38',
        'dbname' => 'test2',
        'charset' => 'utf8',
    ],
    'application' => [
        'baseUri' => '/',
        'publicUrl' => 'simple-admin.sitchi.dev',
        'appDir' => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'formsDir' => APP_PATH . '/forms/',
        'helpersDir' => APP_PATH . '/helpers/',
        'libraryDir' => APP_PATH . '/library/',
        'migrationsDir' => APP_PATH . '/migrations/',
        'modelsDir' => APP_PATH . '/models/',
        'viewsDir' => APP_PATH . '/views/',
        'cacheDir' => BASE_PATH . '/cache/',
        'cryptSalt' => 'eEAfR|_&G&f,+vU]:jFr!!A&+71w1Ms9~8_4L!<@[N@DyaIP_2My|:+.u>/6m,$D'
    ],
    'mail' => [
        'fromName' => 'Simple Admin',
        'fromEmail' => 'info@sitchi.dev',
        'smtp' => [
            'server' => 'smtp.sitchi.dev',
            'port' => 465,
            'security' => 'ssl',
            'username' => '',
            'password' => '',
        ],
    ],
    'logger' => [
        'path' => BASE_PATH . '/logs/',
        'filename' => 'application.log',
        'format' => '%date% [%type%] %message%',
        'date' => 'Y-m-d H:i:s',
    ],
    // Set to false to disable sending emails (for use in test environment)
    'useMail' => false
]);

I tried looking this up but can't seem to find anything relatable. Thanks in advance for the help!


Solution

  • Try changing:

        {
            $user = Users::where('id',1);
            var_dump($user);
        }
    

    to:

        {
            $user = Users::find('id=1');
            var_dump($user);
        }