user can upload only .tsv files.and i want to import this file into mysql with unique value.duplicates are not allowed.how to do this.I tried this code but it gives an error while inserting data.
<?php
include_once("class/dbo.class.php");
$message = null;
$allowed_extensions = array('tsv');
$upload_path = 'uploads';
if (!empty($_FILES['file'])) {
if ($_FILES['file']['error'] == 0) {
// check extension
$file = explode(".", $_FILES['file']['name']);
$extension = array_pop($file);
if (in_array($extension, $allowed_extensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name']))
{
$filename = $upload_path.'/'.$_FILES['file']['name'];
$content = file_get_contents($filename);
$lines = explode("
", $content);
$columns = explode("\t", $lines[0]);
//print_r($columns);
$sql_insert = "
INSERT INTO tsv_table (";
foreach ($columns as $column)
{
if($column == end($columns))
$sql_insert .= "'".addslashes($column)."')";
else
$sql_insert .= "'".addslashes($column)."', ";
}
$sql_insert .= " VALUES
";
$total_lines = count($lines) -1;
for($i=1;$i<$total_lines;$i++)
{
$fields = explode("\t", $lines[$i]);
//print_r($fields);
//exit;
$sql_insert .= "(";
foreach ($fields as $field)
{
if($field == end($fields))
$sql_insert .= "'".addslashes($field)."'";
//else if($field == null)
//$sql_insert .= "'',";
else
$sql_insert .= "'".addslashes($field)."', ";
}
if(($i+1) == $total_lines)
$sql_insert .= ");";
else
$sql_insert .= "),
";
}
$d=new dbo();
dbo.$d->dml($sql_insert);
echo "Data imported successfully.";
}
} else {
$message = '<span class="red">Only .tsv file format is allowed</span>';
}
} else {
$message = '<span class="red">There was a problem with your file</span>';
}
}
?>
<html>
<head>
<title>Upload TSV to MySQL</title>
<link href="css/core.css" rel="stylesheet" type="text/css" />
</head>
<body>
<section id="wrapper">
<form action="" method="post" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" border="0" class="table">
<tr>
<th><label for="file">Select file</label> <?php echo $message; ?></th>
</tr>
<tr>
<td><input type="file" name="file" id="file" size="30" /></td>
</tr>
<tr>
<td><input type="submit" id="btn" class="fl_l" value="Submit" /></td>
</tr>
</table>
</form>
</section>
</body>
</html>
error: 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 ''ID', 'LAST_SCAN_DATE', 'NAME', 'MONSTER_CLASS', 'POWER_LEVEL', 'TRAINER', 'MELE' at line 1
.tsv file contains some fields having null values.
Don't quote the table columns.
Try
$sql_insert = "
INSERT INTO tsv_table (";
foreach ($columns as $column)
{
if($column == end($columns))
$sql_insert .= addslashes($column).")";
else
$sql_insert .= addslashes($column)." ";
}