Problem in variable connection undefined

3

The code is this:

conn file -> Connection to the database:

<?php

class conn
{

    //Atributos de la base de datos
    private $dbname;
    private $host;
    private $user;
    private $pass;
    private $port;

    //Métodos
    public function __construct()
    {
        $this->dbname = "scrum";
        $this->host = "localhost";
        $this->user = "postgres";
        $this->pass = "1234";
        $this->port = "5432";
        try{
        $conexion = new PDO("pgsql:host=".$this->host.
                            ";port=".$this->port.
                            ";dbname=".$this->dbname.
                            ";user=".$this->user.
                            ";password=".$this->pass);
        }catch(Exception $e)
        {
            echo "Tienes el siguiente error:", $e->getMessage();
        }
    }

    public function consultaSimple($sql)
    {
        $conexion->query($sql);
    }

    public function consultaCompleja($sql)
    {
        $consulta = $conexion->query($sql);
        return $consulta;
    }

}

Error trying to include it in the file inicio.php which is a system view in which I make a list. Which tells me that the connection variable is empty; however, the connection is generated.

Driver code:

<?php


include_once("clases/source.php");

class controlador
{
    //Atributos
    private $usuario;

    //Métodos

    public function __construct()
    {
        $this->usuario = new source();
    }

    public function index()
    {
        $resultado = $this->usuario->listar();
        return $resultado;
    }

    public function crear($nombre, $apellido, $username, $pass, $correo)
    {
        $this->usuario->set("nombre",$nombre);
        $this->usuario->set("apellido",$apellido);
        $this->usuario->set("username",$username);
        $this->usuario->set("pass",$pass);
        $this->usuario->set("correo",$correo);

        $resultado = $this->usuario->crear();
        return $resultado;
    }

    public function eliminar($id)
    {
        $this->usuario->set("id",$id);
        $this->usuario->eliminar();
    }

    public function ver($id)
    {
        $this->usuario->set("id",$id);
        $this->usuario->ver();
    }

    public function editar($id)
    {
        $this->usuario->set("id",$id);
        $this->usuario->ver();
        $this->usuario->editar();
    }
}

? >

CRUD source code and functions:

<?php

//Incluimos la clase de conexión
include_once('conn.php');

class source
{
    //Atributos principales
    private $id;
    private $nombre;
    private $apellido;
    private $username;
    private $pass;
    private $correo;

    private $conexion;

    //Métodos CRUD

    //constructor de la classe conexión
    public function __construct()
    {
        $this->conexion = new conn();
    }

    //Fijamos o establecemos el valor del atributo que venga a partir del formulario
    public function set($atributo, $contenido)
    {
        $this->atributo = $contenido;
    }

    //Obtenemos el atributo o dato a través del formulario
    public function get($atributo)
    {
        return $this->atributo;
    }

    public function listar()
    {
        $sql="SELECT * FROM usuario";
        $resultado = $this->conexion->consultaCompleja($sql);
        return $resultado;
    }

    public function crear()
    {
        $sql2 = "SELECT * FROM usuario WHERE username = '{$this->username} or correo = '{$this->correo}' ";
        $resultado = $this->conexion->consultaCompleja($sql2);
        $num = fetchColumn($resultado);

        if (num != 0) {
            return false;
        } else {
            $sql = "INSERT INTO usuario (nombre, apellido, username, correo, password) 
            VALUES ('{$this->nombre}','{$this->apellido}','{$this->username}','{$this->pass}','{$this->correo}')";

            $this->conexion->consultaSimple($sql);
            return true;
        }

    }

    public function eliminar()
    {
        $sql = "DELETE FROM usuario WHERE idusuario = '{$this->id}' ";
        $this->conexion->consultaSimple($sql);
    }

    public function ver()
    {
        $sql = "SELECT * FROM usuario WHERE idusuario = '{$this->id}' ";
        $resultado = $this->conexion->consultaCompleja($sql);
        $row = PDO::FETCH_ASSOC($resultado);

        //Set interno

        $this->id = $row['idusuario'];
        $this->nombre = $row['nombre'];
        $this->apellido = $row['apellido'];
        $this->username = $row['username'];
        $this->pass = $row['password'];
        $this->correo = $row['correo'];
    }

    public function editar()
    {
        $sql = "UPDATE usuario SET nombre = '{$this->nombre}', apellido = '{$this->apellido}', password = '{$this->pass}' 
        WHERE idusuario = '{$this->id}'";

        $this->conexion->consultaSimple($sql);

    }
}

? >

    
asked by Cristian Camilo Cadavid Escarr 14.11.2018 в 16:57
source

1 answer

0

As you have the class, the connection is only available in the constructor. To be able to use it in the other methods you must create a member of the class to which to assign the connection.

For example:

class conn
{

    //Atributos de la base de datos
    private $dbname;
    private $host;
    private $user;
    private $pass;
    private $port;
    private $conexion;

    //Métodos
    public function __construct()
    {
        $this->dbname = "scrum";
        $this->host = "localhost";
        $this->user = "postgres";
        $this->pass = "1234";
        $this->port = "5432";
        try{
        $this->conexion = new PDO("pgsql:host=".$this->host.
                            ";port=".$this->port.
                            ";dbname=".$this->dbname.
                            ";user=".$this->user.
                            ";password=".$this->pass);
        }catch(Exception $e)
        {
            echo "Tienes el siguiente error:", $e->getMessage();
        }
    }

    public function consultaSimple($sql)
    {
        $this->conexion->query($sql);
    }

    public function consultaCompleja($sql)
    {
        $consulta = $this->conexion->query($sql);
        return $consulta;
    }

}
  

NOTE ON SECURITY:

     

The way you are passing your queries is highly vulnerable to   attacks from injection   SQL . It's about a   security hole through which a malicious user   could take control not only of your database, but of everything   the operating system .   It would be useful if you use queries prepared to neutralize that risk.

    
answered by 14.11.2018 / 17:21
source