(PHP/PDO) Separate the Connection file from the Functions

Asked

Viewed 64 times

1

Hello, I am doing a login-registration system with PDO, never used before and I am learning. My question is if you need to separate the file where I connect to the BD, from the functions like registering.

<?php 

    class Connect{
        private $pdo;
        public function __construct($db, $host, $root, $password){
            try{
                $this->pdo = new PDO("mysql:dbname=" . $db . ";host=" . $host, $root, $password);

            }
            catch(PDOException $e){
                echo "Erro com Banco de Dados: ". $e->getMessage();
                exit();
            }
            catch(Exception $e){
                echo "Erro! " . $e->getMessage();
            }
        }
    }

In case I separate how I would communicate the connection to the functions?

  • 1

    Best in a separate file. Imagine that you have several functions ( register User, update User, delete User etc...) in separate files and that you change some parameter in your connection. If your connection is in the same file of these functions you will have to change the parameter in all the files of these functions. In case it is in a separate file just change only in that file. To communicate use a include or require. See how in https://www.php.net/manual/en/function.include.php

  • Thanks for the reply Leo, but I have a question, after giving require in the file Connection within the functions, and trying to execute the function register it give this error Call to a Member Function prepare() on a non-object in online 11, the line is this: $stmt = $this->pdo->prepare("SELECT id FROM users WHERE email = :EMAIL"); I think that is pq n has the $Pdo variable inside that functions file.

  • see if this is what is happening to you https://answall.com/questions/316803/erro-ao-tenta-inserir-call-to-a-member-function-prepare-on-a-non-object

  • The "$this" only works within the class that was instantiated! By the way you’re using $this out of class!

No answers

Browser other questions tagged

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