php - 如何使用 PHP 创建 sql 文件并在 sql 文件中动态编写查询?
问题描述
我正在动态创建 .sql 文件并编写创建表查询,但查询打印在一行中,但我需要类似
$sql = "CREATE TABLE `tbl_demo` (
`system_id` varchar(200) NOT NULL,
`last_name` varchar(200) NOT NULL,
`first_name` varchar(200) NOT NULL,
`full_name` varchar(200) NOT NULL,
`phone` varchar(200) NOT NULL,
`ext` varchar(200) NOT NULL,
`email` varchar(200) NOT NULL,
`dept` varchar(200) NOT NULL,
`site` varchar(200) NOT NULL,
`room` varchar(200) NOT NULL,
`job_title` varchar(200) NOT NULL,
`image` varchar(200) NOT NULL,
`url` varchar(200) NOT NULL,
`active` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
这是我的代码。
<?php
$content = file_get_contents('demo.csv');
$table = 'demo';
$exp = explode("\n", $content);
echo '<pre>';
$headers = explode(',', strtolower(str_replace(' ', '_', $exp[0])));
$table_columns = array();
foreach ($headers as $header) {
$table_columns[] = '`' . $header . '`' . ' VARCHAR(255)';
}
$sql = 'CREATE TABLE ' . '`' . $table . '`' . '(' . implode(',', $table_columns) . ') ENGINE=InnoDB DEFAULT CHARSET=utf8';
print_r($sql);
$myfile = fopen("temp/demo.sql", "a+") or die("Unable to open file!");
fwrite($myfile, $sql);
fclose($myfile);
任何解决方案表示赞赏!
解决方案
在您的 php 中将单引号 (') 更改为双引号 ("),并在行尾添加反斜杠 n (\n)。即
$VarToFile = "This is my line\n";
$VarToFile .= "This is a new line\n";
或者尝试改变
implode(',', $table_columns)
至
implode(",\n", $table_columns)
推荐阅读
- javascript - 无法显示从后端作为对象接收的数据,
- python - 蟒蛇3。如何检查后缀是否在列表中的某些单词中?
- python - Discord 丰富的嵌入按钮
- angular - 具有 5000 个值的 Angular Material Form 自动完成
- c++ - 如何调试`InputPort::Eval(): required InputPort[0] is not connected`
- javascript - Gulp.watch 刷新我的浏览器一次,但之后不再刷新
- r - 循环 | 情节菜单
- prometheus - 普罗米修斯计数和总和指标超过 pushgateway 的重启
- oracle - Orcale 行为与左外连接或条件
- python - 检查帖子被调用的次数