MySQL直接运行但CodeIgniter中的语法错误

时间:2014-02-25 13:58:12

标签: php mysql sql codeigniter mysqli

编辑:我发现问题在于PHP中的多个查询,那么codeigntier的训练是什么?我是否必须自己使用mysqli函数,还是可以使用内置的Codeigniter DB类?

当我将其粘贴到PHPMyAdmin时,我的查询运行正常,但是当我在codeigniter中运行它会导致语法错误,是否有人可以提供帮助?

这是SQL

SET @sql = NULL;

SELECT 
    GROUP_CONCAT(DISTINCT
        CONCAT(
            'MAX(IF(user_fields_to_users.map_field_id=''',field_id,''',user_fields_to_users.map_data,NULL)) AS ', field_name)) INTO @sql

FROM user_custom_fields;

SET @sql = CONCAT('SELECT *
                    ,', @sql, '
                    FROM user_accounts  LEFT JOIN user_fields_to_users ON
                    user_accounts.user_id = user_fields_to_users.map_user_id
          GROUP BY user_accounts.user_id');

PREPARE stmt FROM @sql;

EXECUTE stmt;

我正在使用mysqli与codeigniters $this->db->query();

我得到的错误是

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 'SELECT GROUP_CONCAT(DISTINCT CONCAT( 'MAX(IF(user_fields_t' at line 3

2 个答案:

答案 0 :(得分:0)

更改

'MAX(IF(user_fields_to_users.map_field_id

MAX(IF('user_fields_to_users.map_field_id

答案 1 :(得分:0)

问题是多个查询,这是我使用的代码

$sql = "
SET @sql = NULL;
SELECT 
    GROUP_CONCAT(DISTINCT
        CONCAT(
            'MAX(IF(user_fields_to_users.map_field_id=''',field_id,''',user_fields_to_users.map_data,NULL)) AS ', field_name)) INTO @sql
FROM user_custom_fields;
SET @sql = CONCAT('SELECT *
                    ,', @sql, '
                    FROM user_accounts  LEFT JOIN user_fields_to_users ON
                    user_accounts.user_id = user_fields_to_users.map_user_id
          GROUP BY user_accounts.user_id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
";
if ($this->db->conn_id->multi_query($sql)) {
    do {
        if ($result = $this->db->conn_id->store_result()) {
            $this->selection_total_results = $result->num_rows;
            while ($row = $result->fetch_array()) {
                $result_data[] = $row;
            }
            $result->free();
        }
    } while ($this->db->conn_id->next_result());
}