PHP Notice: Undefined variable: Conn in C: Users Lucas php_Server DB manager.php on line 7

Asked

Viewed 55 times

-1

I’m having a problem connecting to the database, more specific to register a value

I tried to make the connection here

class Dbconnection{

    private $conn;

        function __construct(){
            $this->conn = pg_connect("host='localhost' port='5432' dbname='desafio_softexpert' user='postgres' password='****'") or die("cannot connect to DB");
        }
        public function get_conn(){
            return $this->conn;
        }
}

and here wanted the variable Conn receive the return of the connection, but an error

include("./DB/DBConnection.php");
    $DBConnection = new DBConnection();
    $conn = $DBConnection->get_conn();

    function insert_in_DB($query){
        $result = pg_query ($conn, $query);
        if (!$result)
            echo "query did not execute";
        $rs = pg_fetch_assoc($result);
        if (!$rs)
          echo "0 records";
  • you just forgot to put public in the construction Function even.. <? php class Dbconnection { private $Conn; public Function __Construct() { ... , if you do so it will work normal. in error says that the variable is Undefined or is without definition

1 answer

0

The error was caused by a flaw in your code writing, you eventually forgot to put public in the build function and the variable used in getConn is with undefined value so it caused the error, if you fix just as I show below you will have the problem solved.

<?php 
class DBConnection {
   private $conn;

   public function __construct() {
      $this->conn = pg_connect("host=localhost;port=5432;dbname=desafio_softexpert;user=postgres;password=****") or die("cannot connect to DB");
   }
}

Browser other questions tagged

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