gpt4 book ai didi

php - 是否可以通过 Codeigniter 运行一个长的 .sql 文件?

转载 作者:太空宇宙 更新时间:2023-11-03 11:46:07 24 4
gpt4 key购买 nike

我想在 Codeigniter 3.1.0 中从我的服务器运行一个 .sql 文件。我试过以下

//code to create a DB & this is successful then following ocde 
$query = file_get_contents('./test.sql');
$this->db->query($query);

这是我的test.sql 文件。 https://gist.github.com/rejoan/97dfae1b08116e386b3e6fda97eeb4f7

现在当我运行它时它总是显示错误

A Database Error Occurred

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 'CREATE TABLE user ( id int(11) NOT NULL, test_id int(11) NOT NULL, `' at line 10

CREATE TABLE `test` 
( `id` int(11) NOT NULL,
`name` varchar(250) NOT NULL,
`description` text NOT NULL,
`added` date NOT NULL,
`outdate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `user`
( `id` int(11) NOT NULL,
`test_id` int(11) NOT NULL,
`name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `test` ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `name` (`name`);

ALTER TABLE `user` ADD PRIMARY KEY (`id`),
ADD KEY `test_id` (`test_id`);

ALTER TABLE `test` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37;

ALTER TABLE `user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

ALTER TABLE `user`
ADD CONSTRAINT `FK_user_test` FOREIGN KEY (`test_id`)
REFERENCES `test` (`id`) ON UPDATE NO ACTION;

Filename: C:/xampp/htdocs/spider_clients/system/database/DB_driver.php

Line Number: 691

那么我该如何解决这个问题呢?我有一个通过 PHP 原始代码来执行此操作的想法,但首先我想通过 CI 来解决。有什么想法吗?

** 即使我尝试用单引号替换所有反引号仍然无效

最佳答案

您不能通过 API 运行任何 SQL 文件。即使您拆分文件并在每个 API 调用中运行一个查询也不行。

有些命令可以出现在 SQL 文件中,但它们实际上是 mysql client builtin commands .服务器中的 SQL 解析器无法识别这些命令。

拆分 SQL 文件很棘手。有些 SQL 语句包含文字分号,例如 CREATE TRIGGER。所以你需要更复杂的逻辑来分割文件,它不像preg_split('/;/', $query)那么简单

另一个陷阱:您会发现提交一个只包含 SQL 注释的“查询”会导致错误。

此外,如果您的 SQL 文件太大,使用 file_get_contents() 会耗尽 PHP 的最大内存。

最重要的是,您将浪费大量时间来开发此代码并尝试使其正常工作。您最好利用已经设计用于运行 SQL 脚本的工具:

shell_exec("mysql databasename < ./test.sql");

另见:

关于php - 是否可以通过 Codeigniter 运行一个长的 .sql 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38705017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com