php – JSON print me twice the result of a query

Question:

I have a query in PHP

Model

public static function mostrarSlideIDModel($datosModel, $tabla){

    $stmt = Conexion::conectar()->prepare("SELECT id_slide, marca_slide, desc_slide, liga_slide, imagen_slide FROM $tabla WHERE id_slide = :id");

    $stmt -> bindParam(":id", $datosModel["id"], PDO::PARAM_INT);

    $stmt -> execute();

    return $stmt -> fetch();

    $stmt -> close();
}

Controller:

public static function mostrarSlideIDController(){

        $datosController = array("id"   =>  $_POST['idSlide']);

        $respuesta = SlideModel::mostrarSlideIDModel($datosController, "slides");

        echo json_encode($respuesta);
    }

and when viewing in the browser, in the AJAX response, it prints the information twice, one with an index and the other with the name of the column.

Example:

      "0":48,
      "1":"Nets",
      "2":"Optiviework",
      "3":"http://www.lorem.com/marcas/file.php",
      "4":"banner-131.jpg",
      "id_slide":48,
      "marca_slide":"Nets",
      "desc_slide":"Optiviework",
      "liga_slide":"http://www.lorem.com/marcas/file.php",
      "imagen_slide":"banner-131.jpg"

I do not know how correct this can be, they are from the first times that I handle data in JSON. Hopefully someone can guide me, Thank you.

Answer:

The problem is that the fetch function uses a parameter whose default value returns an associative array and an array with indices. If you want to see only one of these two options, you need to specify the parameter like this:

return $stmt -> fetch(PDO::FETCH_ASSOC);
Scroll to Top