0

I have a php file in which I connect to the database. At the end of the file I require another file in which I also have a connection. This causes the error:

"Fatal error: Cannot redeclare getConnection() (previously declared in..."

It's important for me to use two separate files, so I would like to know how to close the connection before opening a new one (in the file fetched via require).

I thought that closeCursor() would make it work, but unfortunately it doesn't happen. How can I solve this problem?

require('../misc/database.php');
$db = getConnection();

$to = 'bla@gmail.com';
$from = 'bla@gmail.com';
$fromName = 'JaSama';
$subject = 'Informacja o nowym użytkowniku';
$body = 'Zarejestrował się nowy użytkownik. Edytuj ilość mieszkańców w miastach.';
$altBody = 'Zarejestrował się nowy użytkownik. Edytuj ilość mieszkańców w miastach.';
$created = date('Y-m-d H:i:s');

$statement = $db->prepare("INSERT INTO `mailqueue`(`to`, `from`, `fromName`, `subject`, `body`, `altBody`, `created`) VALUES (:to, :from, :fromName, :subject, :body, :altBody, :created)");

$statement->bindValue(':to', $to);
$statement->bindValue(':from', $from);
$statement->bindValue(':fromName', $fromName);
$statement->bindValue(':subject', $subject);
$statement->bindValue(':body', $body);
$statement->bindValue(':altBody', $altBody, PDO::PARAM_STR);
$statement->bindValue(':created', $created);

$statement->execute();
$statement->closeCursor();
require 'mailToDatabaseHandlowiec.php';
oneday
  • 1,599
  • 5
  • 18
  • 29
  • `public function __destruct();` – Daan Aug 13 '14 at 11:48
  • 2
    This is not a connection problem. You are including a file that contains a function name already declared in .... You can't declare same function name twice. I think you are reloading a file already loaded. – Kevin Labécot Aug 13 '14 at 11:49
  • Thanks for pointing that out. It didn't solve the problem, but that was definitely a mistake from my side. – oneday Aug 13 '14 at 11:56
  • Always us `require_one('...');` instead of `require('...');` everywhere in your project – Bellash Jun 05 '18 at 09:29

1 Answers1

3

Not the most beautiful solution, but you can check if the function exists before declaring it:

if (!function_exists('getConnection')) { 
 function getConnection() {
   ....
 }
}

The problem is that you are including a file with the same function twice (maybe even the same file?). Make sure you are using require_once and not require when including the files.

Hampus Brynolf
  • 1,296
  • 11
  • 20
  • The code given didn't work, but making a database2.php with getConnectionTwo and then requiring it worked. I know it's really ugly, but for now it's the only way I managed to solve the problem. I cannot accept your answer as it didn't work, but it was close enough for voting it up as it led me on the right track. – oneday Aug 13 '14 at 12:46