codeigniter插入语法错误

时间:2012-12-28 23:17:20

标签: php mysql codeigniter activerecord

这是我的insert sql语句:

$sql = "
                LOCK TABLE notre_offre WRITE;

                SELECT 
                    @myRight := rgt FROM notre_offre
                WHERE id = " . $this->input->post('category') . ";

                UPDATE notre_offre SET rgt = rgt + 2 WHERE rgt > @myRight;
                UPDATE notre_offre SET lft = lft + 2 WHERE lft > @myRight;
                INSERT INTO notre_offre(id, naziv, lft, rgt) VALUES(null, '" . $this->input->post('title') . "', @myRight + 1, @myRight + 2);
                UNLOCK TABLES;
                ";

        $query = $this->db->query($sql);

但是我遇到语法错误:

"Error Number: 1064

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 @myRight := rgt FROM notre_offre WHERE id = 2; UPD' at line 3

这是什么问题?这完全适用于phpmyadmin和cmd。 “

2 个答案:

答案 0 :(得分:2)

具体不知道Codeigniter,但您可能无法一次发送多个SQL命令。尝试使用单独的LOCK电话发送单个SELECTquery()等命令。

答案 1 :(得分:1)

您可能需要对此进行调整,但是这些内容应该让您开始在数据库中创建存储过程,而不是每次都在尝试查询它:

DROP PROCEDURE IF EXISTS `InsertNode`;
DELIMITER $$
CREATE DEFINER=`db_user`@`localhost` PROCEDURE `InsertNode` (
    pParentCategory VARCHAR(50),
    pCategory VARCHAR(50),
    pTitle VARCHAR(50)
)
    COMMENT 'Inserts a node into a hierarchical table'
    LANGUAGE SQL
    NOT DETERMINISTIC
    MODIFIES SQL DATA
    SQL SECURITY DEFINER
BEGIN
    DECLARE myRight INTEGER;

    START TRANSACTION;
    SELECT `rgt` INTO myRight
      FROM `notre_offre`
      WHERE `id` = pParentCategory;

    UPDATE `notre_offre` SET `rgt` = `rgt` + 2 WHERE `rgt` > myRight;
    UPDATE `notre_offre` SET `lft` = `lft` + 2 WHERE `lft` > myRight;
    INSERT INTO `notre_offre` (`id`, `naziv`, `lft`, `rgt`)
        VALUES (pCategory, pTitle, myRight + 1, myRight + 2);

    SELECT `pCategory` AS "id", pTitle as "myRight",
        (myRight + 1) AS "lft", (myRight + 2) AS "rgt";
    COMMIT;
END $$
DELIMITER ;

请注意,您只需要定义此一次,而不是每次要插入节点时。因此,您可以从您最喜欢的数据库GUI工具(如PhpMyAdmit,MySQL Workbench等)运行它。之后,要插入节点,而不是尝试将其直接插入表中,您可以这样称呼它:

CALL `InsertNode`('Televisions', 'Game Consoles', 'User-defined Title');

就像我说的那样,根据表中的确切字段,您可能需要添加参数并调整上面的过程才能完全按照您的需要进行操作。不过,这应该是一个好的开始。