Home > php教程 > php手册 > body text

php函数mysql_query批量执行多句sql语句

PHPz
Release: 2018-10-08 15:26:39
forward
789 people have browsed it

正常情况下用php的mysql_query函数是不能批量执行多句CREATE TABLE之类的语句的;

而有些场景;比如说有一个sql备份文件、又或是程序初始化时创建数据表结构的时候需要批量执行文件中的sql语句;

解决这个问题可以用explode函数按';'号把sql语句拆成数组;再通过循环执行mysql_query即可;因为每句sql都是以';'号结束的;

但是考虑到sql语句中可能有实体符号  之类的;如果按';'号来拆;容易误伤;所以用preg_split正则来拆更靠谱;

示例环境:

sql文件:./thinkbjy.sql

        $sql_array=preg_split("/;[\r\n]+/", file_get_contents('./thinkbjy.sql'));
        foreach ($sql_array as $k => $v) {
           mysql_query($v,$link);
           echo mysql_error().'<br>';
        }
Copy after login

执行 echo mysql_error().'
';用来查看是否有错误;

白俊遥博客

更多相关教程请访问 php编程从入门到精通全套视频教程

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!