Hello,

I have experience in codeigniter, and in it just set the settings in database.php and you connect to the database. In zend, I have no idea.

Bootstrap.php

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{


protected function _initDB() {

       $dbConfig = new Zend_Config_Ini(APPLICATION_PATH . '/configs/db.ini');
       $dbAdapter = Zend_Db::factory($dbConfig->adapter, array(
            'host'     => $dbConfig->hostname,
            'username' => $dbConfig->username,
            'password' => $dbConfig->password,
            'dbname'   => $dbConfig->dbname
        ));

        My_Db_Table_Abstract::setDefaultAdapter($dbAdapter);

        Zend_Registry::set('db', $dbAdapter);


        if (APPLICATION_ENV == 'development') {
            $profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
            $profiler->setEnabled(true);
            $dbAdapter->setProfiler($profiler);
        }
    }


      public function _initRouter()
        {
            $front = Zend_Controller_Front::getInstance();
            $router = $front->getRouter();

        }



}





<?php

class Application_Model_MBT extends Zend_Db_Table_Abstract 
{

    /**
        Inserts city if does not exist (assuming all city names are unique)
    */

    private function get_city_id($city_name) 
    {
        $stmt = $db->query(
            'SELECT id FROM cities WHERE city = ? LIMIT 1',
            array($city_name)
        );

        $rows = $stmt->fetchAll();

        return $rows;
    }


    public function insert_city($city_name)
    {
        $city = $this->get_city_id($city_name);


        if (empty($city))
        {
            $stmt = $db->query(
                'INSERT INTO cities (id, city) VALUES (DEFAULT, ?)',
                array($city_name)
            );

            //has to be some function for last insert id, but this will be ok as well
            $city = $this->get_city_id($city_name);

            //inserted so must be one row
            $city_id = $city[0]['id'];
        }
        else {
            $city_id = $city[0]['id'];
        }

        return $city_id;
    }

    /* if not exists */
    public function insert_team($id, $cities_id, $name, $web_page) 
    {

        $team = $this->get_team($id);

        if (empty($team)) {

            $stmt = $db->query(
                'INSERT INTO teams (id, cities_id, name, web_page) VALUES (?, ?, ?, ?)',
                array($id, $cities_id, $name, $web_page)
            );      
        }


    }

    private function get_team($id) 
    {
        $stmt = $db->query(
            'SELECT id FROM teams WHERE id = ? LIMIT 1',
            array($id)
        );

        $rows = $stmt->fetchAll();

        return $rows;
    }

    public function insert_player() 
    {
        //TODO:
    }

}

Here is the model code, but it does not know what is $db. I cant even create a constructor in model, I am getting errors. In the contructor I was placing

$db = new Zend_Db_Adapter_Pdo_Mysql(array(
    'host'     => '127.0.0.1',
    'username' => 'webuser',
    'password' => 'xxxxxxxx',
    'dbname'   => 'test'
));

but even blank constructor thorws errros:

 function __construct() {

   }

In contrucktor its wrong to connect to database, it should be somewhere more general. But I cannot find a normal tutorial for this.

I am getting error:

Uncaught exception 'Zend_Exception' with message 'Security check: Illegal character in filename' in E:\projektai\php projektai\htdocs\zend-test\library\Zend\Loader.php:303

How in the world can I quicly find if it does not even show what file name is bad?

I mande fresh instalation of my application and folowred the tutotrials:

http://net.tutsplus.com/tutorials/php/zend-framework-from-scratch/

http://net.tutsplus.com/tutorials/php/zend-framework-from-scratch-models-and-integrating-doctrine-orm/

I ran
zf configure db-adapter [...]

and it was without errors at least , so I refreshed the page and get appliocation error. I went to application.ini, and turned on erro messages, and the message is:

Exception information:

Message: Adapter name must be specified in a string

Stack trace:

#0 E:\projektai\php projektai\htdocs\zend-database\application\controllers\IndexController.php(14): Zend_Db::factory(NULL)
#1 E:\projektai\php projektai\htdocs\zend-database\library\Zend\Controller\Action.php(133): IndexController->init()
#2 E:\projektai\php projektai\htdocs\zend-database\library\Zend\Controller\Dispatcher\Standard.php(268): Zend_Controller_Action->__construct(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http), Array)
#3 E:\projektai\php projektai\htdocs\zend-database\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#4 E:\projektai\php projektai\htdocs\zend-database\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#5 E:\projektai\php projektai\htdocs\zend-database\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#6 E:\projektai\php projektai\htdocs\zend-database\public\index.php(26): Zend_Application->run()
#7 {main}  
Request Parameters:

array (
  'controller' => 'index',
  'action' => 'index',
  'module' => 'default',
)  

This is where I don't understand again what is wrong.

OK, I am in this place:

By line

$mbt = new Application_Model_MBT();

I get error:

Message: No adapter found for Application_Model_MBT

Model file exists, what could be wrong there. I already spent 3 hours trying to figure out how to execute at least one sql query.

I have removed extending:

class Application_Model_MBT// extends Zend_Db_Table_Abstract 

Now the

$mbt = new Application_Model_MBT();

does not throw error. But I cannot call functions. I made print_r($mbt) and it prints empty object:

Application_Model_MBT Object
(
)

But there are function ins the model, so why there is no functions in that object?

ok lets try this what stack overflow says:

http://stackoverflow.com/questions/3481442/zend-newbie-question-no-adapter-found-for

protected function _initDB() {

       $dbConfig = new Zend_Config_Ini(APPLICATION_PATH . '/configs/db.ini');
       $dbAdapter = Zend_Db::factory($dbConfig->adapter, array(
            'host'     => $dbConfig->hostname,
            'username' => $dbConfig->username,
            'password' => $dbConfig->password,
            'dbname'   => $dbConfig->dbname
        ));

        My_Db_Table_Abstract::setDefaultAdapter($dbAdapter);

        Zend_Registry::set('db', $dbAdapter);


        if (APPLICATION_ENV == 'development') {
            $profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
            $profiler->setEnabled(true);
            $dbAdapter->setProfiler($profiler);
        }
    }


      public function _initRouter()
        {
            $front = Zend_Controller_Front::getInstance();
            $router = $front->getRouter();

        }

} 





resources.db.adapter = mysqli
resources.db.params.host = localhost
resources.db.params.username = username of mysql(default root)
resources.db.params.password = password of mysql(default blank means '')
resources.db.params.dbname = test

of course set my host, etc.

and guess what - no working.

Just shows blank page, not even an error. When I remove this, my page loads again.

BTW there is no such files as db.ini, but is application.ini. I tried appliocation ini to use, but did not change anything.

I tried
print_r($dbConfig); die;

right after assignment. Still white page :(

another example from same stack overflow page:

$db = Zend_Db::factory('Pdo_Mysql', array(
             'host'     => '127.0.0.1',
             'username' => 'root',
             'password' => '',
             'dbname'   => 'schema_mbt'
        )); 
         Zend_Db_Table::setDefaultAdapter($dbAdapter);

don't know where to put, so put in controller.

Does not throw errrors.

But then

    $mbt = new Application_Model_MBT();

is empty, as written earlier.

So I trie to uncomment, so it extends some database adapter or something like that:

class Application_Model_MBT extends Zend_Db_Table_Abstract 

and guess what ladies and gentelmen. You are ritht - error again!

Application error

Exception information:

Message: No adapter found for Application_Model_MBT

The question - is it posible to connect to the database with zend framework? :D

finally at least something works!

$db = new Zend_Db_Adapter_Pdo_Mysql(array(  //from zend documentation
            'host'     => '127.0.0.1',
            'username' => 'root',
            'password' => '',
            'dbname'   => 'schema_mbt'
        ));

        $sql = 'SELECT * FROM cities';

        $result = $db->fetchAll($sql); 

        print_r($result);

this code is in one of the controller functiosn. It works, take data from table :) But its bad, I will have to use this connection creating in every function? And also I cannot use the model? In MVC I should run queries in models, but I cannot because object of the model is empty. I am sick of this, I will have to put model functions in controller, otherwise I will take ages to make the task.

ok,

unfortunately this was not enought for the task to use just controllers. I need to somehow load model.

I now know that model name must be table name.

Reading the docs again:
http://framework.zend.com/manual/en/zend.db.table.html

"If you don't specify the table name, it defaults to the name of the class. If you rely on this default, the class name must match the spelling of the table name as it appears in the database."

example:

class bugs extends Zend_Db_Table_Abstract
{
    // table name matches class name
}

ok, look simple. In my database there is table players. Lets try:

class players extends Zend_Db_Table_Abstract 
{

}

in index controller function:

$mbt = new players();

I get error that calss players is not found. Ok, google for that error, found decent page, at least looks like:

http://stackoverflow.com/questions/2475912/model-class-is-not-found-in-zend-framework-project-quickstart

few anwers are saying to add this. So if even few answers, this is likely to work. I add:

protected function _initResourceAutoloader()
    {
         $autoloader = new Zend_Loader_Autoloader_Resource(array(
            'basePath'  => APPLICATION_PATH,
            'namespace' => 'Application',
         ));

         $autoloader->addResourceType( 'model', 'models', 'Model');

         return $autoloader;
    }

And...
get and error:

Fatal error: Class 'players' not found in E:\projektai\php projektai\htdocs\zend-database\application\controllers\IndexController.php on line 55

How should I feel? Its still not found. WHy is that? WHat I am doing wrong? I cannot see. This is sick framework. Class not found - what an inforational message..

finally I have a solution how to connect to a model. One person helped, so it is much easier when experienced person helps than to google on my own.

The steps was:

Change the class name to Application_Model_players, without prefix Application_Model_ it did not work. But don't know why, in some examples there was without that prefix.
After changing of course adapter not found error, which I saw milion times.
This error in human language means - model is found, but database adapter is not found - adapter is something like connection to database or something like that as I understood. (At first adapter for me was in my eyes the thing which we put into socket and charge mobile phone, of course I knew that this is not then case :) )

To fix no adapter found error, I had to add database connection settting application.ini production part, because production is selected in the index.php file:

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

I didn't pay attention too much to this, because there was line

[development : production]

so I thouth they are somehow asociated anyway, so do not matter much is it production or development. But I guess this line meanst that development inherits setting from the production, so it migth be to the one side. But not sure, its just guess.

In the model, where I run sql statemenst I have to use getAdapter

$stmt = $this->getAdapter()->query(
            'SELECT teams.id
                FROM  `teams`'
        );

getAdater probalby is the thing who gets the database connection settings from application.ini and connects to the database.

How easy is to do when you have good explainations, and how waste of time is when you don't know error message meanings and trying examples from google does not work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.