Create Stored Procedures with PDO in PHP

后端 未结 3 1159
一向
一向 2020-12-19 10:31

I am reading a TEXT file from PHP and trying to execute commands from it, like creating a DB and all the tables and procedures it has. My code creates the tables but does no

相关标签:
3条回答
  • 2020-12-19 10:48

    In an effort to keep on topic and answer the question

    DELIMITER $$
    DROP PROCEDURE IF EXISTS `add_hits`$$
    CREATE DEFINER=`root`@`localhost` PROCEDURE `add_hits`( In id varchar(255))
    BEGIN
       select hits into @hits from db_books where Book_ID = id;
       update db_books set hits=@hits+1 where Book_ID = id;
    END$$
    

    The first occurance of $$ will terminate the DDL so

    DROP PROCEDURE IF EXISTS `add_hits`$$
    

    So I think it should be

    DELIMITER $$
    DROP PROCEDURE IF EXISTS `add_hits`;
    CREATE DEFINER=`root`@`localhost` PROCEDURE `add_hits`( In id varchar(255))
    BEGIN
       select hits into @hits from db_books where Book_ID = id;
       update db_books set hits=@hits+1 where Book_ID = id;
    END
    $$
    
    0 讨论(0)
  • 2020-12-19 10:52

    PHP only allows you to execute one query at a time normally, so delimiters are not necessary

    $pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $pdo->exec('DROP PROCEDURE IF EXISTS `add_hits`');
    $pdo->exec('CREATE DEFINER=`root`@`localhost` PROCEDURE `add_hits`( In id varchar(255))
     BEGIN
     declare hits_bk int;
     select hits into hits_bk from db_books where Book_ID = id;
     update db_books set hits=hits_bk+1 where Book_ID = id;
     END');
    
    0 讨论(0)
  • 2020-12-19 11:02

    Well, PMA Helped me with answering this Question of my own.
    To overcome this you need to remove the delimiter part of the procedure, so that your queries become like:

     DROP PROCEDURE IF EXISTS `add_hits`;
     CREATE DEFINER=`root`@`localhost` PROCEDURE `add_hits`( In id varchar(255))
     BEGIN
     declare hits_bk int;
     select hits into hits_bk from db_books where Book_ID = id;
     update db_books set hits=hits_bk+1 where Book_ID = id;
     END;
    

    Now the queries will work.
    Thanks to @Your Common Sense and @RiggsFolly for helping out.

    0 讨论(0)
提交回复
热议问题