dongzhila3786 2013-05-16 15:39
浏览 48
已采纳

有没有一种聪明的方法可以在分号分隔的mysql中运行多个查询; [重复]

This question already has an answer here:

Is there a smart way to run multiple MySQL queries separated by a semicolon (;) in a string via PHP, perhaps with a PHP-function - and how can such a PHP function be coded? The queries MUST be separated with a colon in a string, and there should be no manual edit of that as accepted in other questions since the solution is supposed to handle this format (that's the point).

$multi_query = "INSERT INTO `stuff_5_firm` (firm_id, firmname) VALUES (0, 'Hey LTD');
INSERT INTO `stuff_6_invoice` (invoice_id, firm_id, amount) VALUES (0, 0, 500);
INSERT INTO `stuff_7_order` (order_id, firm_id, when) VALUES (0, 0, '2018-05-05'); ";
</div>
  • 写回答

1条回答 默认 最新

  • duang8642 2013-05-16 16:38
    关注

    Here's a working solution

    <?php
    function function_that_does_multiple_queries($mq, $dblink) {
        // if a new line follows the ; then $q_array = explode(';
    ',$mq); is suggested since queries can contain ; below
        $q_array = explode(";",$mq);
        /* 
        //To check structure of array
        echo "<pre>";
        print_r($q_array);
        echo "</pre>";
        exit();
        */
        foreach($q_array as $q){
            $q = trim($q);
            $r[] = mysqli_query($dblink,$q);
        }
        return $r;
    }
    $multi_query = "CREATE TABLE IF NOT EXISTS `stuff_5_firm` (
      `firmid` int(11) NOT NULL,
      `firm_name` varchar(256) NOT NULL,
      `firm_invoice_adr` text NOT NULL,
      `firm_invoice_email` varchar(256) NOT NULL,
      `firm_admin_con_to_userid` int(16) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    CREATE TABLE IF NOT EXISTS `stuff_6_invoice` (
      `invoiceid` int(11) NOT NULL,
      `inv_date` datetime NOT NULL,
      `inv_due` datetime NOT NULL,
      `inv_paid` datetime NOT NULL,
      `inv_amount` int(11) NOT NULL,
      `inv_text` int(11) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
    
    function_that_does_multiple_queries($multi_query, $dblink);
    
    ?>
    

    Probably it's wiser to use mysqli_multi_query which is explained here http://php.net/manual/en/mysqli.multi-query.php (thanks to @andrewsi).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊