首页 > 解决方案 > 如何使用 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

解决方案


在您的 php 中将单引号 (') 更改为双引号 ("),并在行尾添加反斜杠 n (\n)。即

$VarToFile = "This is my line\n";
$VarToFile .= "This is a new line\n";

或者尝试改变

implode(',', $table_columns) 

implode(",\n", $table_columns) 

推荐阅读