php - 从 HTML 表中的存储过程 MySql PHP 获取结果

标签 php mysql stored-procedures

我在数据库中有存储过程:

DELIMITER $$

USE `billing`$$

DROP PROCEDURE IF EXISTS `Pivot`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `Pivot`(
    IN tbl_name VARCHAR(99),       -- table name (or db.tbl)
    IN base_cols VARCHAR(99),      -- column(s) on the left, separated by commas
    IN pivot_col VARCHAR(64),      -- name of column to put across the top
    IN tally_col VARCHAR(64),      -- name of column to SUM up
    IN where_clause VARCHAR(99),   -- empty string or "WHERE ..."
    IN order_by VARCHAR(99)        -- empty string or "ORDER BY ..."; usually the base_cols
    )
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
    -- Find the distinct values
    -- Build the SUM()s
    SET @subq = CONCAT('SELECT DISTINCT ', pivot_col, ' AS val ',
                    ' FROM ', tbl_name, ' ', where_clause, ' ORDER BY 1');
    -- select @subq;
    SET @cc1 = "CONCAT('SUM(IF(&p = ', &v, ', &t, 0)) AS ', &v)";
    SET @cc2 = REPLACE(@cc1, '&p', pivot_col);
    SET @cc3 = REPLACE(@cc2, '&t', tally_col);
    -- select @cc2, @cc3;
    SET @qval = CONCAT("'\"', val, '\"'");
    -- select @qval;
    SET @cc4 = REPLACE(@cc3, '&v', @qval);
    -- select @cc4;
    SET SESSION group_concat_max_len = 10000;   -- just in case
    SET @stmt = CONCAT(
            'SELECT  GROUP_CONCAT(', @cc4, ' SEPARATOR ",\n")  INTO @sums',
            ' FROM ( ', @subq, ' ) AS top');
     SELECT @stmt;
    PREPARE _sql FROM @stmt;
    EXECUTE _sql;                      -- Intermediate step: build SQL for columns
    DEALLOCATE PREPARE _sql;
    -- Construct the query and perform it
    SET @stmt2 = CONCAT(
            'SELECT ',
                base_cols, ',\n',
                @sums,
                ',\n SUM(', tally_col, ') AS Total'
            '\n FROM ', tbl_name, ' ',
            where_clause,
            ' GROUP BY ', base_cols,
            '\n WITH ROLLUP',
            '\n', order_by
        );
    SELECT @stmt2;                    -- The statement that generates the result
    PREPARE _sql FROM @stmt2;
    EXECUTE _sql;                     -- The resulting pivot table ouput
    DEALLOCATE PREPARE _sql;
    -- For debugging / tweaking, SELECT the various @variables after CALLing.
END$$

DELIMITER ; 

当我传递 SQL 语句时,我想捕获带有列标题的行中的最终结果,并将其传递到 PHP 上的 HTML 表输出。

CALL Pivot('production', 'product_name', 'market', 'forcast_qty', \"WHERE production_date = '2015-12-31'\", '');

到目前为止,当我编写以下过程来获取输出时,我得到的是一个数组,但不是存储过程的最终结果。

if(isset($_POST['planned_forecast']))
{
if(isset($_POST['production_date'])){ $date_prod = $_POST['production_date']; } 
$stmt = $DB_con->prepare("CALL Pivot('production', 'product_name', 'market', 'forcast_qty', \"WHERE production_date = '2015-12-31'\", '');");
$stmt->execute();
while ($row  = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
print_r($row);
}
echo '
<thead>';
   echo '
</thead>
';
echo '
<tbody>
   ';
   echo '
   <tr>
      ';
      echo '
      <td></td>
      ';
      echo '
   </tr>
   ';
   echo '
</tbody>
';
echo '</table>';
echo '<input hidden="true" name="date_prod" type="text" value="'.$date_prod.'"/>';
echo '<button type="submit" class="btn btn-default waves-effect waves-light" name="btn-editforcast" id="btn-editforcast">Update</button>';
}

结果:

Array ( [0] => Array ( [@stmt] => SELECT GROUP_CONCAT(CONCAT('SUM(IF(market = ', '"', val, '"', ', forcast_qty, 0)) AS ', '"', val, '"') SEPARATOR ", ") INTO @sums FROM ( SELECT DISTINCT market AS val FROM production WHERE production_date = '2015-12-31' ORDER BY 1 ) AS top ) )

enter image description here

最佳答案

我认为您可以简化存储过程并使用如下内容:

DELIMITER $$

USE `billing`$$

DROP PROCEDURE IF EXISTS `Pivot`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `Pivot`(
    IN tbl_name VARCHAR(99),       -- table name (or db.tbl)
    IN base_cols VARCHAR(99),      -- column(s) on the left, separated by commas
    IN pivot_col VARCHAR(64),      -- name of column to put across the top
    IN tally_col VARCHAR(64),      -- name of column to SUM up
    IN where_clause VARCHAR(99),   -- empty string or "WHERE ..."
    IN order_by VARCHAR(99)        -- empty string or "ORDER BY ..."; usually the base_cols
    )
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN

    -- Prepare the "pivot" part of the query
    SET @stmt = CONCAT(

        "SELECT GROUP_CONCAT(\" SUM(\" ",
        "                    \"   CASE WHEN ", pivot_col, "='\", ", pivot_col, ", \"'\"  ",
        "                    \"         THEN ", tally_col, "\"  ",
        "                    \"         ELSE 0\"  ",
        "                    \"    END\"  ",
        "                    \") AS '\", ", pivot_col, ", \"'\n\") as stmt FROM (select distinct ", pivot_col, " FROM ", tbl_name, ") A INTO @sum_clause"    
    );


    PREPARE _sql FROM @stmt;
    EXECUTE _sql;                     
    DEALLOCATE PREPARE _sql;

        -- Prepare and execute the query itself
    SET @stmt = CONCAT(
        "SELECT ", base_cols, ", ", 
        @sum_clause,
        ", SUM(", tally_col, ") as 'Total qty'"
        " FROM ", tbl_name, " \n" ,
        where_clause, "\n",
        " GROUP BY ", base_cols
        );

    PREPARE _sql FROM @stmt;
    EXECUTE _sql;                     
    DEALLOCATE PREPARE _sql;

END$$

DELIMITER ;  

我不能保证它适用于所有情况,但它适用于您在示例中使用的参数,并产生与原始问题中相同的结果。

关于php - 从 HTML 表中的存储过程 MySql PHP 获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34395552/

相关文章:

mysql - MariaDB/MySQL 中 CREATE PROCEDURE 中的神秘错误

php - ZF2+Doctrine2 - 在 Mac 上突然出现错误 : "Doctrine\ORM\EntityManager"; no instance returned

mysql - 数据库设计/SQL 优化 : WHERE <id> NOT IN (thousands of IDs)

entity-framework - Entity Framework 中具有连接数据的存储过程

php - 具有特殊字符的 Codeigniter 查询

php - 在我的网络服务器上打包文件

mysql - Mysql 存储过程中的未知系统变量 "no_more_data"

php - 设置公共(public)类变量

php - 在用 PHP 创建的 iPhone 上解析 XML

php - 使用codeigniter在mysql中插入复选框值