How can I get the comments of the articles with two different tables with php PDO MVC?

1

This is my first message in this forum.

I have to print the results of several sections, for example, the articles in the "fes_articles" table and the comments in the "fes_comments" table. At the beginning they ask me first on the left to take out the last article with their image and comments and I do it this way:

file- > controllers / managerBlog.php

class BlogControllers{

 static public function ctrMostrarArticulosBlog(){

        $tabla1 = "fes_articles";               
        $tabla2 = "fes_files";
        $tabla3 = "fes_comments";       
        $idCategoria = 44;
        $idArticulo = 452; /*Prueba con artículo con dos comentarios*/          
        $idArticulo = 668;/*ÚLTIMO ARTÍCULO ACTUAL EN LA BASE DE DATOS, 0 comentarios*/     

        $respuesta = BlogModels::mdlMostrarArticulosBlog($tabla1, $tabla2, $tabla3, $idCategoria, $idArticulo);

        return $respuesta;

    } 
}

file - > models / gestorBlog.php

<?php

require_once "conexion.php";

class BlogModels{

static public function mdlMostrarArticulosBlog($tabla1, $tabla2, $tabla3, $idCategoria, $idArticulo){

        $stmt = Conexion::conectar()->prepare("SELECT $tabla1.id, $tabla1.pages, $tabla1.categories, $tabla1.title, $tabla1.content, $tabla1.tags, $tabla2.name, $tabla2.ext, $tabla2.descriere, $tabla2.idx
            FROM $tabla1 
            INNER JOIN $tabla2 ON $tabla1.id = $tabla2.idx          
            WHERE $tabla1.categories = :idCategoria 
            AND $tabla1.id = :idArticulo
            ORDER by $tabla1.id DESC LIMIT 1 "); 

 $stmt -> bindParam(":idCategoria", $idCategoria, PDO::PARAM_STR);//Preguntar si se pone INT
        $stmt -> bindParam(":idArticulo", $idArticulo, PDO::PARAM_STR);//Preguntar si se pone INT
        $stmt -> bindParam(":comentarios", $comentarios, PDO::PARAM_STR);

        $stmt -> execute();

        return $stmt -> fetch(); 

        $stmt -> close();

        $stmt = null;    
}

/*COMENTARIOS*/

public function mdlTotalComentariosArticulosBlog($tabla1, $tabla3, $idCategoria,$idArticulo){

        $stmt = Conexion::conectar()->prepare("SELECT $tabla1.id, $tabla1.pages, $tabla1.categories, $tabla1.title, $tabla1.content, $tabla1.tags, $tabla3.id, $tabla3.categories, $tabla3.articles, COUNT($tabla3.content) as totalComentarios FROM $tabla1 
            INNER JOIN $tabla3 ON $tabla1.id = $tabla3.articles             
            WHERE $tabla1.id  = :idArticulo 
            ORDER by $tabla3.id");
        $stmt -> bindParam(":idArticulo", $idArticulo, PDO::PARAM_STR);                 

        $stmt -> execute();

        return $stmt->fetchAll();

        $stmt -> close();

        $stmt = null;   

    }
}

and finally in the view file:

file - > views / modules / blog.php

<?php
/* -- ARTÍCULO PRINCIPAL GRANDE -- */   

                $respuestaArticulos = BlogControllers::ctrMostrarArticulosBlog();

                $contenidoArticulos = substr($respuestaArticulos["content"], 0, 185);   

                echo'<section class="bloque-izq-cat">
                <article class="art-cat featured Article">
                <a class="thumb-art-cat" href="">

                <img  src="views/images/'.$respuestaArticulos['name'].'.'.$respuestaArticulos['ext'].'" title="'.$respuestaArticulos['descriere'].' " alt="'.$respuestaArticulos['descriere'].'"  />

                <span class="fecha-encima-art-cat dateOverlay">02 Jun 2017</span>
                <span class="num-encima-art-cat nrOverlay">0</span>
                </a>
                <h2 class="titulo-art-cat"><a href="">'.$respuestaArticulos["title"].'</a></h2>
                <p class="text-art-cat"><a href="">'.$contenidoArticulos.'</a></p>';                                

                /* ----- COMENTARIOS -------*/
                /*Aquí ver como puedo hacer para no repetir esta parte ya que vuelvo a traer los datos anteriores para consultar los comenatarios*/
                $tabla1 = "fes_articles";                                   
                $tabla3 = "fes_comments";               
                $idCategoriaComments = 44;
                $idArticuloComments = 452;/*Artículo de prueba con 2 comentarios*/                  
                $idArticulo = 668; /*ÚLTIMO ARTÍCULO ACTUAL EN LA BASE DE DATOS con 0 comentarios*/             

                $cantidadComentarios = BlogModels::mdlTotalComentariosArticulosBlog($tabla1, $tabla3, $idCategoriaComments, $idArticuloComments);

                foreach ($cantidadComentarios as $row => $item) {
                    $totalComentarios = $item["totalComentarios"];
                    if($totalComentarios > 1){
                        echo '<p class="fecha-y-comentario-mini-art-cat">junio 02, 2017 / <a href="">'.$totalComentarios.' comentarios</a></p>
                        </article>
                        </section>';
                    }

                    else if($totalComentarios == 1){
                        echo '<p class="fecha-y-comentario-mini-art-cat">junio 02, 2017 / <a href="">'.$totalComentarios.' comentario</a></p>

                        </article>
                        </section>';
                    }

                    else if($totalComentarios == 0){

                        echo '<p class="fecha-y-comentario-mini-art-cat">junio 02, 2017 / <a href="">0 comentarios</a></p>          
                        </article>
                        </section>';

                    }

                }
                /* ----- FIN COMENTARIOS -------*/

                /* -- FIN ARTÍCULO PRINCIPAL GRANDE -- */   
?>

So far so good because if I put the test article 452 I get perfectly printed and with the notice of 2 comments and if I put the last or even others I get 0 or the corresponding number.

Now I have to do the same with the rest of the comments to print, for example in the area on the right come 5 articles (from the 2nd most current to the 6th) and do the same to show how many comments each one has. However for more laps that I give I am not able.

For example the file of the following articles I use it like this:

file- > controllers / managerBlog.php

public function ctrMostrarMiniArticulosBlog(){      

        $tabla1 = "fes_articles";
        $tabla2 = "fes_files";
        $idCategoria = 44;      

        $respuesta = BlogModels::mdlMostrarMiniArticulosBlog($tabla1, $tabla2, $idCategoria);

        return $respuesta;

    }

file- > models / gestorBlog.php

public function mdlMostrarMiniArticulosBlog($tabla1, $tabla2, $idCategoria){


        $stmt = Conexion::conectar()->prepare("SELECT $tabla1.id, $tabla1.pages, $tabla1.categories, $tabla1.title, $tabla1.content, $tabla1.tags, $tabla2.name, $tabla2.ext, $tabla2.descriere, $tabla2.idx
            FROM $tabla1 
            INNER JOIN $tabla2 ON $tabla1.id = $tabla2.idx          
            WHERE $tabla1.categories = :idCategoria             
            ORDER by $tabla1.id DESC LIMIT 1, 5");      

        $stmt -> bindParam(":idCategoria", $idCategoria, PDO::PARAM_STR);           

        $stmt -> execute();

        return $stmt->fetchAll();

        $stmt -> close();

        $stmt = null;       

    }  

file- > views / modules / blog.php

 $respuestaMiniArticulos = BlogControllers::ctrMostrarMiniArticulosBlog();

                echo '<section class="bloque-der-cat">';    

                foreach ($respuestaMiniArticulos as $row => $item) {
                    echo '<article class="mini-art-cat mini Article">
                    <a class="thumb-mini-art-cat" href="">      
                    <img  src="views/images/'.$item['name'].'.'.$item['ext'].'" title="'.$item['descriere'].' " alt="'.$item['descriere'].'"  /></a>
                    <h3 class="titulo-mini-art-cat"><a href="">'.$titulo.'</a></h3>
                    <p class="fecha-y-comentario-mini-art-cat">junio 01, 2017 / <a href="">';                   

                /* ----- COMENTARIOS MINI ARTÍCULOS -------*/

                /*AQUÍ LA DUDA*/

                /* ----- FIN COMENTARIOS MINI ARTÍCULOS -------*/   
}

The comments table only exists for articles that have comments, that is, if an article id = 452 does not have comments, therefore, the comments table does not exist. Do I have to make a query with two checks then? First one to see if there is that comment id in comments and then another to see if it exists and relate it to the id in the articles table and make a count and finally all that at the same time apply it in a foreach to go making the count

As I said before I have tried several other ways that I do not put here, but in the end I'm getting a mess because I can not give each item with comment its position in the foreach block. How could I get it out or improve it?

Greetings.

    
asked by José Carlos - kahlito 10.02.2018 в 16:39
source

1 answer

0

After doing several tests, combinations, queries etc etc I think I managed to get it out by doing tests in the previous queries in mysql through phpmyadmin.

Now the files and codes are like this:

file- > controllers / managerBlog.php

<?php

/*=============================================
CONTROLADOR DEL BLOG 
=============================================*/

class BlogControllers{

static public function ctrMostrarCategoriaBlog(){

        $tabla4 = "fes_categories";
        $idCategoria = 44;

        $respuesta = BlogModels::mdlMostrarCategoriaBlog($tabla4, $idCategoria);

        return $respuesta;

    }   

static public function ctrMostrarArticulosBlog(){       

        $tabla1 = "fes_articles";
        $tabla2 = "fes_files";
        $tabla3 = "fes_comments";       
        $idCategoria = 44;

        $respuesta = BlogModels::mdlMostrarArticulosBlog($tabla1, $tabla2, $tabla3, $idCategoria);

        return $respuesta;

    }

    static public function ctrMostrarMiniArticulosBlog(){       

        $tabla1 = "fes_articles";
        $tabla2 = "fes_files";
        $tabla3 = "fes_comments";       
        $idCategoria = 44;      

        $respuesta = BlogModels::mdlMostrarMiniArticulosBlog($tabla1, $tabla2, $tabla3, $idCategoria);

        return $respuesta;

    }
}
?>

file - > models / gestorBlog.php

<?php

require_once "conexion.php";

/*=============================================
MODELO DEL BLOG
=============================================*/

class BlogModels{

    static public function mdlMostrarCategoriaBlog($tabla4, $idCategoria){

        $stmt = Conexion::conectar()->prepare("SELECT id, title, content FROM $tabla4 WHERE id = :idCategoria");

        $stmt -> bindParam(":idCategoria", $idCategoria, PDO::PARAM_STR);

        $stmt -> execute();

        return $stmt->fetch();

        $stmt -> close();

        $stmt = null;       

    }

public function mdlMostrarArticulosBlog($tabla1, $tabla2, $tabla3, $idCategoria){       


        $stmt = Conexion::conectar()->prepare("SELECT $tabla1.id, $tabla1.title, $tabla1.categories, $tabla1.content, $tabla1.tags, $tabla2.name, $tabla2.ext, $tabla2.descriere, $tabla2.idx,(SELECT COUNT($tabla3.content) as totalComentarios FROM $tabla3 WHERE $tabla3.articles = $tabla1.id and $tabla1.categories = :idCategoria) AS totalComentariosFinal
            FROM $tabla1
            INNER JOIN $tabla2 ON $tabla1.id = $tabla2.idx          
            WHERE $tabla1.categories = :idCategoria         
            ORDER by $tabla1.id DESC LIMIT 1");

        $stmt -> bindParam(":idCategoria", $idCategoria, PDO::PARAM_STR);               

        $stmt -> execute();     

        return $stmt->fetch();

        $stmt -> close();

        $stmt = null;       

    }  

    public function mdlMostrarMiniArticulosBlog($tabla1, $tabla2, $tabla3, $idCategoria){

        $stmt = Conexion::conectar()->prepare("SELECT $tabla1.id, $tabla1.title, $tabla1.categories, $tabla1.content, $tabla1.tags, $tabla2.name, $tabla2.ext, $tabla2.descriere, $tabla2.idx,(SELECT COUNT($tabla3.content) as totalComentarios FROM $tabla3 WHERE $tabla3.articles = $tabla1.id and $tabla1.categories = :idCategoria) AS totalComentariosFinal
            FROM $tabla1
            INNER JOIN $tabla2 ON $tabla1.id = $tabla2.idx          
            WHERE $tabla1.categories = :idCategoria         
            ORDER by $tabla1.id DESC LIMIT 1, 5");      

        $stmt -> bindParam(":idCategoria", $idCategoria, PDO::PARAM_STR);                   

        $stmt -> execute();

        return $stmt->fetchAll();

        $stmt -> close();

        $stmt = null;       

    }  

?>

file - > views / modules / blog.php

<?php                   

                /*=============================================
                VISTA DEL BLOG 
                =============================================*/ 

                /* -- CATEGORÍA -- */

                $respuestaCategoria = BlogControllers::ctrMostrarCategoriaBlog();

                echo '<header class="encabezado-cat cat-1">
                    <h1 class="nombre-cat"><a class=\'cursor-none\' href=\'javascript:void(0)\' rel="nofollow"><span>'.$respuestaCategoria["title"].'</span></a></h1>
                    </header>
                    <article class="textPage">'.$respuestaCategoria["content"].'</article>';        

                /* -- ARTÍCULO PRINCIPAL GRANDE -- */   

                $respuestaArticulos = BlogControllers::ctrMostrarArticulosBlog();

                $totalComentarios = $respuestaArticulos["totalComentariosFinal"];
                $contenidoArticulos = substr($respuestaArticulos["content"], 0, 185);   


                echo'<section class="bloque-izq-cat">
                    <article class="art-cat featured Article">
                    <a class="thumb-art-cat" href="">

                    <img  src="views/images/'.$respuestaArticulos['name'].'.'.$respuestaArticulos['ext'].'" title="'.$respuestaArticulos['descriere'].' " alt="'.$respuestaArticulos['descriere'].'"  />

                    <span class="fecha-encima-art-cat dateOverlay">02 Jun 2017</span>
                    <span class="num-encima-art-cat nrOverlay">0</span>
                    </a>
                    <h2 class="titulo-art-cat"><a href="">'.$respuestaArticulos["title"].'</a></h2>
                    <p class="text-art-cat"><a href="">'.$contenidoArticulos.'</a></p>';                

                /* ----- COMENTARIOS -------*/

                echo '<p class="fecha-y-comentario-mini-art-cat">junio 02, 2017 / <a href="">'.$totalComentarios.' comentarios Hola</a></p>         
                    </article>
                    </section>';    

                /* ----- FIN COMENTARIOS -------*/      

                /* -- FIN ARTÍCULO PRINCIPAL GRANDE -- */   


                /* -- MINI ARTÍCULOS--*/

                $respuestaMiniArticulos = BlogControllers::ctrMostrarMiniArticulosBlog();

                echo '<section class="bloque-der-cat">';    

                foreach ($respuestaMiniArticulos as $row => $item) {

                    $titulo = $item["title"];
                    $totalComentarios = $item["totalComentariosFinal"];

                    echo '<article class="mini-art-cat mini Article">
                    <a class="thumb-mini-art-cat" href="">      
                    <img  src="views/images/'.$item['name'].'.'.$item['ext'].'" title="'.$item['descriere'].' " alt="'.$item['descriere'].'"  /></a>
                    <h3 class="titulo-mini-art-cat"><a href="">'.$titulo.'</a></h3>
                    <p class="fecha-y-comentario-mini-art-cat">junio 01, 2017 / <a href="">';


                    /* ----- COMENTARIOS MINI ARTÍCULOS -------*/

                    echo '<p class="fecha-y-comentario-mini-art-cat">junio 02, 2017 / <a href="">'.$totalComentarios.' comentarios Hola</a></p>';

                    /* ----- FIN COMENTARIOS MINI ARTÍCULOS -------*/               

                    echo' </article>';

                }

                echo '</section>';  

                /* -- FIN MINI ARTÍCULOS--*/     
?>

By making a new query with a select to count the comments within the same select for the articles I have managed to minimize the process and it seems that now it goes correctly.

Could this way of doing it even be improved? Greetings.

    
answered by 12.02.2018 в 21:01