How to call the connection within a function

Asked

Viewed 450 times

1

defines.php

$HOST = "localhost";
$USER = "root";
$PASS = "";
$DB = "banco";

config.php

function conexao(){
    try{
        include_once("defines.php");
        $conn = new PDO("mysql:host=".$HOST.";dbname=".$DB."",$USER,$PASS);
    }catch(PDOException $e){
        $e->getMessage();
    }
    return $conn;
}

func.php

I’m trying to include this connection in this role

include "pdo/config.php";
$conn = conexao ();

function noticias($conn){
    // Faz algo
}

But it’s making a lot of mistakes

Notice: Undefined variable: HOST in /home/vol8_6/epizy.com/epiz_23239906/htdocs/Pdo/config.php on line 5

Notice: Undefined variable: DB in /home/vol8_6/epizy.com/epiz_23239906/htdocs/Pdo/config.php on line 5

Notice: Undefined variable: USER in /home/vol8_6/epizy.com/epiz_23239906/htdocs/Pdo/config.php on line 5

Notice: Undefined variable: PASS in /home/vol8_6/epizy.com/epiz_23239906/htdocs/Pdo/config.php on line 5

Notice: Undefined variable: Conn /home/vol8_6/epizy.com/epiz_23239906/htdocs/Pdo/config.php on line 9

Warning: Missing argument 1 for noticias(), called in /home/vol8_6/epizy.com/epiz_23239906/htdocs/aqv/lancamentos.php on line 11 and defined in /home/vol8_6/epizy.com/epiz_23239906/htdocs/func/var.php on line 4

  • 1

    Not loading the file defines.php. Exchange the include/include_once for require_once. This way it generates an error and for the execution of the script if it cannot include the file. By the way, pq vc made a file only with the data of the connection and another with the connection? Being that the file of the connection was named config.php... Let’s face it: user, password, and other database information are also settings. They should be in the file config.php, nay?!

  • In your php files you have the tag "<? php ?>" ?

  • @Wandersonrodrigo We must assume so. Otherwise the PHP interpreter would not generate the errors... Right?!

  • has yes Wanxerson, did not work Lip, same errors, about the defines file was to make the code get cleaner

  • I’ll formulate an answer and you give a Ctrl+C > Ctrl+V. I can change the structure of your project a little?!

  • @Lipespry if it works yes, because I will call this function on more than one page

Show 1 more comment

1 answer

1

Following the structure of your project:

/pdo/defines.php
/pdo/config.php
/funcs.php

/Pdo/defines.php

<?php

$conexaoPDO = array(
    'drive' => 'mysql',     // Se for usar MySQL, não precisa mexer (ah vá)
    'host' => 'localhost',  // Host do banco de dados. Localmente = localhost
    'usuario' => 'root',    // Usuário
    'senha' => '',          // Senha
    'database' => 'teste',  // Nome do banco de dados
    'charset' => 'utf8'     // Charset - Recomendo usar o mesmo em todo seu projeto
);

/Pdo/config.php

<?php

function getPDO() {
    try {
        require_once('defines.php');
        $pdoConn = new PDO(
            (
                $conexaoPDO['drive']
                .':host='
                .$conexaoPDO['host']
                .';dbname='
                .$conexaoPDO['database']
            ),
            $conexaoPDO['usuario'],
            $conexaoPDO['senha'],
            array(
                \PDO::MYSQL_ATTR_INIT_COMMAND => (
                    'SET NAMES '
                    .$conexaoPDO['charset']
                )
            )
        );
        $pdoConn->setAttribute(
            \PDO::ATTR_ERRMODE,
            \PDO::ERRMODE_EXCEPTION
        );

        return $pdoConn;

    } catch (PDOException $e) {
        die($e->getMessage());
        die('Erro ao conectar-se com o banco de dados!');
    }
}

/func.php

<?php

require_once('pdo/config.php');

function noticias($pdoConn){
    // Faz algo
}

//getPDO()->prepare('SELECT ...');
//getPDO()->execute();
//getPDO()->query('SELECT ...');

That should solve your problem once and for all.


Considerations to be taken:

  1. If you put the PDO connection inside some function and the data coming from another file, you must load it (defines.php) inside the function. If you are going to click outside the function, you need to declare the file variables defines.php as global. More details in the documentation: PHP - Scope of variables;

  2. Every time you carry something that is defendant in the operation of your project, use require or require_once. The difference that the require_once will not allow the same file to be loaded more than once. If it fails to load the file, it stops the execution of the script and returns an error (php.ini must be configured to display the error directly on the page you are browsing);

  3. Breaking, I enhanced your PDO connection. More details in the documentation: PHP - PDO.

  4. I replicated the codes and the structure in my Github/sopt-as-call-a-connection-in-a-function. You can download right there.

  • Error 500 in config.php

Browser other questions tagged

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