How do I connect to another database using the connection I already have

-1

How do I connect to another database using the connection I already have and work perfectly in another database?

When I change only the connection name appears:

  

Notice: Undefined variable: conn2 in C: \ Program Files (x86) \ EasyPHP-5.3.6.0 \ www \ store \ function \ online2.php 22

Here is the code:

<?php
function conecta2( ){
  if(!defined("HOST")){
     define('HOST','localhost');
  }
  if(!defined("BD")){
     define('BD','cadastro');
  }
  if(!defined("USER")){
     define('USER','root');
  }
  if(!defined("PASS")){
     define('PASS','');
  }
try {
$conn2 = new PDO('mysql:host='.HOST.';dbname='.BD.'', ''.USER.'', ''.PASS.'');
$conn2->exec("SET NAMES 'utf8'");
}
catch(PDOException $erro){
echo $erro->getMessage();
}
return $conn2; // esta é a linha 22
}
    
asked by anonymous 25.02.2016 / 17:37

1 answer

2

Your return must be included within try :

//...
try {
    $conn2 = new PDO('mysql:host='.HOST.';dbname='.BD.'', ''.USER.'', ''.PASS.'');
    $conn2->exec("SET NAMES 'utf8'");
    return $conn2;
}
catch(PDOException $erro){
    //echo $erro->getMessage();
    return false;
}

The error occurs because its conn2 variable is created within try . If the connection to the database fails, which probably happened, it is not instantiated and the interpreter jumps to block catch stating the error occurred.

Notice that I commented the line:

echo $erro->getMessage();

Use this line only for debugging; I also added within the block catch o return false; if the connection to the database is not possible.

So you can do, for example, the connection verification:

$conn = conecta2();
if($conn) {
    //operações CRUD
} else {
    echo "Não foi possível conectar a base de dados.";
}
    
25.02.2016 / 17:51