title: PHP - Best Way To Handle Multiple database in Zend framework 2
body: <p>We are creating a web application using Zend Framework 2 with multiple databases. I have a <code>core</code> database which loads info of all customers. This database contains <code>customer</code> table. The fields of customer table are ::</p>
  
  <ol>
  <li>id</li>
  <li>username</li>
  <li>password</li>
  <li>database_name</li>
  <li>customer_name</li>
  <li>...................</li>
  </ol>
  
  <p>When a customers logs in, i have to load his database name from the <code>core</code> database and then make query requests to the database. </p>
  
  <p>I cannot have multiple adapters either, because all customers have their own database which i have to load from <code>customer</code> table of <code>core_db</code>!</p>
  
  <p>I thought i would prefix database name with table name.</p>
  
  <p>I tried this in <code>Module.php</code>:</p>
  
  <pre><code>"CategoryTableGateway" =&gt; function ($sm) {
                  $dbAdapter = $sm-&gt;get("Zend\Db\Adapter\Adapter");
                  $resultSetPrototype = new ResultSet();
                  $resultSetPrototype-&gt;setArrayObjectPrototype(new Category());
                  return new TableGateway("databasename.category", $dbAdapter, null, $resultSetPrototype);
              }
  </code></pre>
  
  <p>I had configured default database in my <code>config\autoload\database.global.php</code> as this:</p>
  
  <pre><code>    'db' =&gt; array(
      'driver'         =&gt; 'Pdo',
      'dsn'            =&gt; 'mysql:dbname=core_db;host=localhost',
      'driver_options' =&gt; array(
          PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES \'UTF8\''
      ),
  )
  </code></pre>
  
  <p>I got a exception like:</p>
  
  <pre><code>Base table or view not found: 1146 Table 'core_db.databasename.category' doesn't exist.
  </code></pre>
  
  <p>And then, I removed <code>dbname=core_db</code> from <code>config\autoload\database.global.php</code>.</p>
  
  <p>Now, I got another exception like:</p>
  
  <pre><code>SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
  </code></pre>
  
  <p>So how do i handle that situation in Zend Framework 2. I am new to Zend Framework 2.</p>
  
  <p><code>Edit</code>: I got the solution to my question by myself.</p>
  
  <p>To connect to table of another schema you need to pass <code>TableIdentifier</code> instead of table!</p>
  
  <p>For example, </p>
  
  <p>Instead of:</p>
  
  <pre><code> $CategoryTableGateway = new TableGateway("category", $dbAdapter, null, $resultSetPrototype);
  </code></pre>
  
  <p>You have to do:</p>
  
  <pre><code>$CategoryTableIdentifier = new TableIdentifier('category','dbname');
  $CategoryTableGateway = new TableGateway($CategoryTableIdentifier, $dbAdapter, null, $resultSetPrototype);
  </code></pre>
  
  <p>Hope It Works!</p>