title: Multiple database connections with PDO
body: <p>I'm trying to connect to several databases at the same time and am having problems. This query works fine with my local site. (It doesn't have a username or password, thus the "root, root.")</p>
  
  <pre><code>$dsn = "mysql:host=localhost;dbname=gbase;charset=utf8";
   $opt = array(
    PDO::ATTR_ERRMODE            =&gt; PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC
   );
  
   $pdo = new PDO($dsn,'root','root', $opt);
  </code></pre>
  
  <p>I used <a href="https://stackoverflow.com/questions/274892/how-do-you-connect-to-multiple-mysql-databases-on-a-single-webpage">this discussion</a> as a guide in creating a multiple-database query. I replaced all the code above with this:</p>
  
  <pre><code>try {
   $db1 = new PDO('mysql:dbname=gbase;host=localhost', 'root', 'root');
   $db2 = new PDO('mysql:dbname=glife;host=localhost', 'root', 'root');
  } catch (PDOException $ex) {
    echo 'Connection failed: ' . $ex-&gt;getMessage();
  }
  </code></pre>
  
  <p>But I get these error messages:</p>
  
  <p><strong>Notice:</strong> Undefined variable: pdo in /Applications/MAMP/htdocs/gx/index.php on line 164</p>
  
  <p><strong>Fatal error:</strong> Call to a member function prepare() on null in /Applications/MAMP/htdocs/gx/index.php on line 164</p>
  
  <p>And this is line 64:</p>
  
  <pre><code>$stm = $pdo-&gt;prepare("SELECT A.Site, A.URL, A.Title, A.Article
   FROM 1_about A
  </code></pre>
  
  <p>I suspect that I need to somehow integrate my new code with my original code, rather than simply replace it. However, I don't understand what's going on. Can someone show me the correct way to write a multiple-database query?</p>
  
  <p><strong>Edit: Below is the entire code I'm using.</strong></p>
  
  <pre><code>try {
   $db1 = new PDO('mysql:dbname=geobase;host=localhost', 'root', 'root');
   $db2 = new PDO('mysql:dbname=geolife;host=localhost', 'root', 'root');
  } catch (PDOException $ex) {
   echo 'Connection failed: ' . $ex-&gt;getMessage();
  }
  
  $stm = $pdo-&gt;prepare("SELECT A.Site, A.URL, A.Title, A.Article
   FROM 1_about A
   WHERE A.Site = 'g1' AND A.URL = 'webranger'");
  $stm-&gt;execute(array(
   // 'MyURL'=&gt;'%'.$MyURL.'%'
  ));
  
  while ($row = $stm-&gt;fetch())
  {
   $Article = $row['Article'];
  }
  
  echo $Article;
  </code></pre>