2

I am creating grids on my website using the JqueryBootgrid Plugin and PHP as backend code. I could bind a grid of "users" and add buttons for adding, deleting, and editing. That works properly. The problem is with the following tables:

table productos

id_producto (PK) nombre descripcion_larga descripcion_corta imagen imagen_logo stock id_categoria (FK)

table precios_productos

id_precio (PK) fecha_precio precio id_producto (FK)

table categorias

id_categoria (PK) descripcion

I want to create a grid which shows all the products with their most "current" prices. So I have been done a query with temporary table which works properly on phpMyAdmin and return the right products with their most recent prices. But this query does not work on my php code and thus the grid does not work either.

THE QUERY:

 CREATE TEMPORARY TABLE IF NOT EXISTS fec_val AS (SELECT pre.id_producto, max(pre.fecha_precio) fecha FROM precios_productos pre GROUP BY pre.id_producto); SELECT p.id_producto, p.nombre, p.descripcion_larga, p.descripcion_corta, cat.descripcion, p.imagen, p.stock, p.imagen_logo, pre.precio FROM fec_val fv INNER JOIN productos p ON fv.id_producto = p.id_producto INNER JOIN precios_productos pre ON pre.id_producto = p.id_producto INNER JOIN categorias cat ON cat.id_categoria = p.id_categoria WHERE pre.fecha_precio = fv.fecha

And here you have the full php code backend for the bootgrid:

<?php try {

    //Configuracion de la base de datos

    $hostname = "localhost";
    $username = "facundo";
    $password =  "******";
    $database  = "facundo";
    

    $conn = new PDO("mysql:host=localhost;dbname={$database}", $username, $password);

    //Parametro de la consulta

    $search         = "";
    $where      = "";
    $order_by       = "id_producto";        
    $rowCount   = 10;//Cantidad de resultados por default
    
    
    //Envia parametros adicionales en el pack json 
    $debug          = TRUE;

    
    //Obtengo la cantidad de resultados para mostrar por pagina
    
    if (! empty( $_REQUEST['rowCount']))
    {
        $rowCount = $_REQUEST['rowCount'];
    }
    
    //calculate the low and high limits for the SQL LIMIT x,y clause
    if ( !empty($_REQUEST['current']) )
    {
        $current        =   $_REQUEST['current'];
        $limit_lower    =   ($current * $rowCount) - ($rowCount);
        $limit_hight    =   $limit_lower + $rowCount;
    }
    
    if ($rowCount   ==  -1)
    {
        $limit=""; //no limit
    }else{
        $limit = "LIMIT {$limit_lower},{$limit_hight}"; 
    }


    //Genera el order by 
    if (isset($_REQUEST['sort']) && is_array($_REQUEST['sort']) )
    {
        $order_by= "";
        
        foreach($_REQUEST['sort'] as $key=> $value)
            {
                    $order_by.="{$key} {$value}";
            }
    }

    
    //Buscador
    $search_phrase = $_REQUEST['searchPhrase'];
    
    
    if (!empty($search_phrase))
    {
        
        $search = trim($search_phrase);
        
        $where  = "WHERE pre.fecha_precio = fv.fecha OR nombre LIKE '".$search."%' OR descripcion_larga LIKE '".$search."%' OR id_producto LIKE '".$search."%' ";
        
    }//close if
            

    //Consulta para obtener los resultados      
    //$sql = "SELECT id_producto, nombre, descripcion_larga, descripcion_corta, descripcion, imagen, stock, imagen_logo, precio FROM productos INNER JOIN precios_productos ON productos.id_precio = precios_productos.id_precio INNER JOIN categorias ON productos.id_categoria = categorias.id_categoria {$where} ORDER BY {$order_by} {$limit}";
    //$sql = "CREATE TEMPORARY TABLE IF NOT EXISTS fec_val AS (SELECT pre.id_producto, max(pre.fecha_precio) fecha FROM precios_productos pre GROUP BY pre.id_producto); SELECT p.id_producto, p.nombre, p.descripcion_larga, p.descripcion_corta, cat.descripcion, p.imagen, p.stock, p.imagen_logo, pre.precio FROM fec_val fv INNER JOIN productos p ON fv.id_producto = p.id_producto INNER JOIN precios_productos pre ON pre.id_producto = p.id_producto INNER JOIN categorias cat ON cat.id_categoria = p.id_categoria {$where} ORDER BY {$order_by} {$limit}";   
    //$sql = "SELECT * FROM productos INNER JOIN categorias on productos.id_categoria = categorias.id_categoria INNER JOIN precios_productos ON precios_productos.id_producto = productos.id_producto";
    $sql = "CREATE TEMPORARY TABLE IF NOT EXISTS fec_val AS (SELECT pre.id_producto, max(pre.fecha_precio) fecha FROM precios_productos pre GROUP BY pre.id_producto); SELECT p.id_producto, p.nombre, p.descripcion_larga, p.descripcion_corta, cat.descripcion, p.imagen, p.stock, p.imagen_logo, pre.precio FROM fec_val fv INNER JOIN productos p ON fv.id_producto = p.id_producto INNER JOIN precios_productos pre ON pre.id_producto = p.id_producto INNER JOIN categorias cat ON cat.id_categoria = p.id_categoria WHERE pre.fecha_precio = fv.fecha"
    $stmt               =   $conn->prepare($sql);
    $stmt->execute();
    $results_array  =   $stmt->fetchAll(PDO::FETCH_ASSOC);


    //Obtengo el total de resultados
    $query_count    = "SELECT count(*) FROM productos";
    $nRows              =   $conn->query($query_count)->fetchColumn();

    //Devuelvo la informacion en formato json

    $pack                           = array();
    $pack["current"]            = $current;
    $pack["rowCount"]       = $rowCount;
    $pack["rows"]               = $results_array;
    $pack["total"]                  = $nRows;
    
    
    //Info de debug
    
    if($debug)
    {
        $pack['query']              = $sql;
        $pack['query_total']        = $query_count;     
    }
    
    echo json_encode($pack);
    }catch(PDOException $e) {

    echo 'SQL PDO ERROR: ' . $e->getMessage();}?>

I would like to know how can I fix that. Thanks.

Community
  • 1
  • 1

0 Answers0