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

Asked

Viewed 38 times

-1

How do I connect to another database using the connection I already have and works 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 funcao conecta2.php on line 22

Here’s 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
}

1 answer

2

Your Return must be included within the 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 variable conn2 is created within the try. If the database connection fails, which probably happened, it is not instantiated and the interpreter jumps to the block catch stating which error occurred.

Notice I commented on the line:

echo $erro->getMessage();

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

So it will be possible to do, for example, the connection check:

$conn = conecta2();
if($conn) {
    //operações CRUD
} else {
    echo "Não foi possível conectar a base de dados.";
}
  • It worked! Thank you

  • @Claytoncampos knows to mark the answer as right?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.