PHP-mysql error (PDO) [closed]

0

I have a question, I have this class:

<?php
class DB{
//Función para conectar con la base de datos
public static function ejecutaConsulta($sql) {
    $servidor = "localhost";
    $dbname = "vehiculos";
    $usuario = "root";
    $contrasena = "";
    try {
        $opc = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
        $dsn = "mysql:host=$servidor;dbname=$dbname";
        $dwes = new PDO($dsn, $usuario, $contrasena, $opc);
        $dwes->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $resultado = $dwes->query($sql);
    } catch (PDOException $e) {
        echo "Se ha producido un error: " . $e->getMessage();
    }
    return $resultado;
}

//Función para obtener los coches
public static function obtieneCoches(){
    $sql = "SELECT coche.bastidor, coche.marca, coche.descripcion, coche.tipo, tipo.nombre FROM coche, tipo WHERE coche.tipo = tipo.cod";
    $resultado = self::ejecutaConsulta($sql);
    $coches = array();
    if($resultado){
        // Añadimos un elemento por cada pedido leido
        $row = $resultado->fetch_object();
        while ($row != null){
            $coches[] = $row;
            $row = $resultado->fetch_object();
        }
    }
    return $coches;
}}?>

As you can see, I collect data from two different tables and when I collect them I try to save them as an array of objects, but when I run it, I get the following error:

  

Fatal error: Call to undefined method PDOStatement :: fetch_object () in /opt/lampp/htdocs/DWES/xajax_DanielGomez/Exercise1/DB.php on line 28

Can someone help me and explain what is happening? As you can see in PHP and mysql I am new.

Greetings and thanks in advance

    
asked by dgomez 02.06.2017 в 17:36
source

1 answer

2

The problem is that $resultado is an object of type PDOStatement and method want to use is not called fetch_object , but the correct name is fetchObject

Solution:

Modify the obtieneCoches method in the following way:

...
public static function obtieneCoches(){
    $sql = "SELECT coche.bastidor, coche.marca, coche.descripcion, coche.tipo, tipo.nombre 
    FROM coche, tipo WHERE coche.tipo = tipo.cod";
    $resultado = self::ejecutaConsulta($sql);
    $coches = array();
    if($resultado){

        // Añadimos un elemento por cada pedido leido
        $row = $resultado->fetchObject();
        while ($row != null){
            $coches[] = $row;
            $row = $resultado->fetchObject();
        }
    }
    return $coches;
}
...
    
answered by 02.06.2017 / 17:42
source