php - 使用 MySQL 和 PHP 在 CSV 文件上传时动态创建表

标签 php html mysql csv

我尝试先通过创建表名来创建表。但我想我创建的表名称并不能帮助我的代码做到这一点,并且它给出了以下错误:

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 '' at line 1

这是我的代码:

<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>next change</title>
<style type="text/css">
.auto-style1 {
    margin-left: 0px;
}
.auto-style2 {
    margin-left: 13px;
}
.auto-style3 {
    margin-left: 6px;
}
.auto-style4 {
    margin-left: 276px;
}
</style>
</head>

<body>

<form action="" method="POST">
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    Session Starting Year :&nbsp; 20
    <select name="session" style="width: 48px" class="auto-style1">
    <option value="14">14</option>
    <option value="15">15</option>
    </select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

     Program: 

    <select class="auto-style2" name="course" style="width: 141px">
    <option value="mca">MCA</option>
    <option value="btcse">B.Tech. CSE</option>
    <option value="btece">B. Tech. ECE</option>
    <option value="msccs">MSc. Comp. Sc.</option>
    </select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    Semester:   
    <select name="semester" class="auto-style3" style="width: 55px">
                <option value="sem1">I</option>
                <option value="sem2">II</option>
                <option value="sem3">III</option>
                <option value="sem4">IV</option>
                <option value="sem5">V</option>
                <option value="sem6">VI</option>
                <option value="sem7">VII</option>
                <option value="sem8">VIII</option>
            </select>

            <br/>
            <br/>
            <input name="create" type="submit" value="Create" class="auto-style4" style="width: 77px" />
    </form>
<?php
$table="";
if($_POST['create']){
$yr=$_POST['session'];
$course=$_POST['course'];
$sem=$_POST['semester'];
$table=$yr.$course.$sem;
}
$table=mysql_real_escape_string($table);
echo $table."<br/";

$dbName = "test";

 $conn = mysql_connect('localhost','root','','test');
 if (!$conn) {
 die('Could not connect to MySQL: ' . mysql_error());
}

 mysql_select_db($dbName) or die(mysql_error());
//Upload the csv file
if (isset($_POST['submit'])) {
    if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
        echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
    }

//get the first row fields
$fields = "";
$fieldsInsert = "";
if (($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE) {
if(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    $fieldsInsert .= '(';
    for ($c=0; $c < $num; $c++) {
        $fieldsInsert .=($c==0) ? '' : ', ';
        $fieldsInsert .="`".$data[$c]."`";
        $fields .="`".$data[$c]."` varchar(10) DEFAULT NULL,";
    }

    $fieldsInsert .= ')';
}


//drop table if exist
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))>=1) {
  mysql_query('DROP TABLE IF EXISTS '.$table) or die(mysql_error());
}

//create table
$sql = "CREATE TABLE `".$table."` (
          ".$fields."
          PRIMARY KEY (`roll`)
        ) ";

$retval = mysql_query( $sql, $conn );

if(! $retval )
{
  die('Could not create table: ' . mysql_error());
}
else {
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

            $num = count($data);
            $fieldsInsertvalues="";
            //get field values of each row
            for ($c=0; $c < $num; $c++) {
                $fieldsInsertvalues .=($c==0) ? '(' : ', ';
                $fieldsInsertvalues .="'".$data[$c]."'";
            }
            $fieldsInsertvalues .= ')';
            //insert the values to table
            $sql = "INSERT INTO ".$table." ".$fieldsInsert."  VALUES   ".$fieldsInsertvalues;
            mysql_query($sql,$conn);   
    }
    echo 'Table Created';   
}

fclose($handle);

}
print "Import Done.";
}else {

    print "Upload new csv by browsing to file and clicking on Upload<br />\n";

    print "<form enctype='multipart/form-data' action='next_change.php' method='post'>";

    print "File name to import:<br />\n";

    print "<input size='50' type='file' name='filename'><br />\n";

    print "<input type='submit' name='submit' value='Upload'></form>";


}
?>


</body>

</html>

我做错了什么?

最佳答案

您的 $fieldsInsert 变量应包含在“(”和“)”内。请参阅 mysql insert http://dev.mysql.com/doc/refman/5.7/en/insert.html 的语法

关于php - 使用 MySQL 和 PHP 在 CSV 文件上传时动态创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40938647/

相关文章:

html - CSS 网格 - 基于行的放置

mysql - WSO2 DSS - 如何在插入/更新查询(成功或失败)后添加响应?

mysql - 将 findall 与计算每个父级的每个关系子级进行 Sequelize

php - INSERT SELECT 查询中的自定义值

html - 在没有 flex 的情况下垂直对齐另一个 div 内的 div

php - Composer 不检测 php7,而是使用 5.6。如何设置 CLI 以使用 php7

javascript - JQuery 输入焦点操作

PHP/MySQL : Handling empty sql result in php array

php - mysql_insert_id() 返回 0

php - 使用php bin2hex函数读取bin文件