Error when consulting data inheriting methods

0

Greetings guys. I am working on a project in PHP Oriented to objects with PDO, it turns out that I am doing the tests of the methods and I was presented with an error in the query by id. I proceed to explain my code:

First I have my class Connection in which I have my constructor with the connection and two more methods:

<?php namespace Models;

class Conexion{
    private $con;

    public function __construct(){

        try{
            $this->con = new \PDO('mysql:host=localhost;dbname=poo_pdo','root','');

        }catch(PDOExcepcion $e){
            echo $e->getMessage();
            exit;
        }
    }

    //Metodo para llamar la conexion y decirle que se va a ejecutar una query
    public function consultaSimple($sql){
        $this->con->prepare($sql); 
    }

    //Metodo para retornar lo que se consulte
    public function consultaRetorno($sql){
        $datos= $this->con->prepare($sql);
        return $datos;
    }
}
?>

The next class is the Student's. The method that is presenting me with a problem is what is called view (), it turns out that I am returning false, I have printed with var_dump and it is showing me false, it is not returning anything, this is the class:

<?php namespace Models; 

class Estudiante{

    private $id;
    private $name;
    private $edad;
    private $promedio;
    private $imagen;
    private $fecha;
    private $id_seccion;
    private $con;

    public function __construct(){
        $this->con = new Conexion();
    }

    public function set($atributo, $contenido){
        $this->$atributo = $contenido;
    }

    public function get($atributo){
        return $this->$atributo;
    }

    public function listar(){
        $sql = "SELECT t1.*, t2.nombre as nombre_seccion FROM estudiantes t1 INNER JOIN secciones t2 ON t1.id_seccion = t2.id";
        $datos=$this->con->consultaRetorno($sql);
        return $datos;
    }

    public function add(){
        $sql = "INSERT INTO estudiantes(id,nombres,edad,promedio,img,fecha,id_seccion)
        VALUES(null,:name,:edad,:promedio,:imagen,:fecha,:id_seccion)";
        $this->con->consultaSimple($sql);
    }

    public function delete(){
        $sql = "DELETE FROM estudiantes WHERE id = :id";
        $this->con->consultaRetorno($sql);
    }

    public function edit(){
        $sql = "UPDATE FROM estudiantes SET nombres = :name, edad = :edad, promedio = :promedio, id_seccion = :id_seccion WHERE id = :id ";
        $this->con->consultaSimple();
    }

    public function view(){
        $sql = "SELECT nombres FROM estudiantes WHERE id = :id ";
        $datos = $this->con->consultaRetorno($sql);
        $row = $datos->fetch();
        return $row;
    }

}

As I said the view method is the one that is giving me problems. Through the set () method, I pass parameters to make the query since I'm just testing. I do it this way:

<?php 

require_once "Config/Autoload.php";
Config\Autoload::run();
$est = new Models\Estudiante(); //Instancio la clase
$est->set("id", 3); //Llamo al método set de la clase y le paso los parámetros que quiero consultar
$datos = $est->view();
print $datos['nombres'];
?>

What I want to do is consult the student with id = 3, but as I said it does not show anything on the screen, everything is blank and when I print with var_dump I see that false returns. I need help please thanks

    
asked by Alejo Mendoza 26.12.2017 в 23:08
source

1 answer

0

I will not give you a solution on time because it will depend on how you want to implement things.

Documentation of prepared Judgments

You are doing the prepare but you are missing the bind and the execute .

Example of Conexion :

$this->con->prepare("SELECT nombres FROM estudiantes WHERE id = :id");
$this->con->bindParam(':id', $est->get('id'));
$this->con->execute();

In your code, at no time do you specify the value of :id or any other parameter. For that you have to use -is an option- bindParam() , read the documentation.
On the other hand, with prepare() just not enough, you have to do a execute() to run the query. The fetch() that you do is fine, but first you have to do execute() .

Now, the issue is how you pass the parameters for bind . You could put together quite advanced functions like those with the ORM , but a simple solution would be to add a parameter to consultaSimple and consultaRetorno with a array of binds .

/**
 * $binds por defecto es un array vacío,
 * así que podes no pasar ese parámetro.
 */
public function consultaRetorno($sql, $binds = []) {
    $datos = $this->con->prepare($sql);
    foreach ($binds as $key => $val) {
        $datos->bindParam($key, $val);
    }

    return $datos->execute();
}

Having that method, I do not know what sense it would have to keep maintaining consultaSimple . Keep in mind that none of your consultaSimple are running because they do not have execute() . I would replace them with consultaRetorno() , but I insist, since I do not know exactly what you have in mind, I just throw you examples.

The use would be something like this:

public function view() {
    $sql = "SELECT nombres FROM estudiantes WHERE id = :id";
    $params = [':id' => $this->get('id')];
    $datos = $this->con->consultaRetorno($sql, $params);
    $row = $datos->fetch();

    return $row;
}

Anything warn me and we are correcting what is needed. I have not used PDO directly so there may be errors.

    
answered by 27.12.2017 / 03:06
source