dongpinyao2203 2017-01-25 13:24
浏览 61
已采纳

Mysql数据透视表在PhpMyadmin中完全正常工作但与Php mysqli_query()无关

I've this dynamic MYSQL query building a pivot table that works in phpmyadmin (and SequelPro):

SET SESSION group_concat_max_len = 1000000;
SET @sql = NULL;
SELECT
    GROUP_CONCAT(DISTINCT
    'MAX(CASE WHEN meta_key = "lat_poi" THEN meta_value END) AS lat_poi,
    MAX(CASE WHEN meta_key = "lng_poi" THEN meta_value END) AS lng_poi'
   ) INTO @sql


FROM wp_postmeta;

SET @sql = CONCAT('SELECT posts.post_title, ', @sql, '
               FROM wp_posts posts
                LEFT JOIN wp_postmeta postmeta 
                ON posts.ID = postmeta.post_id
                WHERE (posts.post_type = "poi" AND posts.post_status = "publish")
                GROUP BY posts.ID
               ');

PREPARE stmt FROM @sql;
EXECUTE stmt;

I want to use it in Php to query the database but it gives this error:

string(226) "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @sql = NULL; 
SELECT
   GROUP_CONCAT(DISTINCT
     'MAX(CASE WHEN meta_key = ' at line 2"
 bool(false)

Here's the Php code:

$connection = mysqli_connect("localhost", "db_name", "db_pwd", "db_user");
$query_expression = "
SET SESSION group_concat_max_len = 1000000;
SET @sql = NULL;
SELECT
   GROUP_CONCAT(DISTINCT
     'MAX(CASE WHEN meta_key = \"lat_poi\" THEN meta_value END) AS lat_poi,
      MAX(CASE WHEN meta_key = \"lng_poi\" THEN meta_value END) AS lng_poi'
) INTO @sql


   FROM wp_postmeta;

   SET @sql = CONCAT('SELECT posts.post_title, ', @sql, '
               FROM wp_posts posts
                LEFT JOIN wp_postmeta postmeta 
                ON posts.ID = postmeta.post_id
                WHERE (posts.post_type = \"poi\" AND posts.post_status = \"publish\")
                GROUP BY posts.ID
               ');

   PREPARE stmt FROM @sql;
   EXECUTE stmt;";
$query = mysqli_query($connection, $query_expression);
var_dump(mysqli_error($connection));
var_dump($query);

Any hint?

Thanks in advance...

  • 写回答

1条回答 默认 最新

  • doujuegai8830 2017-01-25 13:33
    关注

    This is not a query but a set of queries.

    Split it into separate statements and run them one by one

    mysqli_query($connection, "SET SESSION group_concat_max_len = 1000000");
    mysqli_query($connection, "SET @sql = NULL");
    $query_expression = "SELECT...";
    $query = mysqli_query($connection, $query_expression);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的