1

这是我的插入 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 完美运行。"

4

2 回答 2

2

具体不了解 Codeigniter,但您可能一次不能发送多个 SQL 命令。尝试通过单独的调用发送个人LOCKSELECT命令。query()

于 2012-12-28T23:19:24.827 回答
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 ;

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

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

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

于 2012-12-29T00:35:41.237 回答