我有一个需要将CSV导入mysql的php应用程序。但是我只能在路径在代码中时导入。但我不希望这样。我不知道我的客户是否有.CSV文件。 你能帮助我吗? 这是我的代码:
<form enctype='multipart/form-data' action="" method='post'onSubmit='getPath();'>
<input type="file" name="file" />
<input type='submit' name='submit' value='Importar'/>
</form>
<?php
$conexao = mysql_connect ("localhost", "root", "") or die (mysql_error());
$bd = mysql_select_db ("wcfleet_demo");
if (isset ($_POST['submit']))
{
$file = $_FILES ['file'] ['name'];
$filepath="C:\\xampp\htdocs\wecreatefleet\\";
$msg = $filepath."".$file; //bind
$handle = fopen ($msg, "r");
$i= 0;
//$caminho = "C:\\xampp\htdocs\wecreatefleet\\teste.csv";
//$abraArq = fopen ($caminho, "r");
if (!$handle)
{
echo ("<p> Arquivo não encontrado! </p>");
}
else
{
while (($valores = fgetcsv ($handle, 100000, ";"))!== false)
{
$lines = file($msg);
if($i>=8)
{
$line = explode (';', $lines[$i]);
$sql = "INSERT INTO via_verde (identificador, matricula, referencia, data_entrada, hora_entrada, entrada, data_saida,
hora_saida, saida, valor, valor_desconto, taxa_iva, operador, servico, data_pagamento, cartao_n)
VALUES ('$line[0]', '$line[1]', '$line[2]', '$line[3]', '$line[4]', '$line[5]', '$line[6]', '$line[7]',
'$line[8]', '$line[9]', '$line[10]', '$line[11]', '$line[12]', '$line[13]', '$line[14]', '$line[15]')";
mysql_query ($sql) or die (mysql_error());
}
$i++;
}
fclose ($handle);
mysql_close($conexao);
echo "Processo finalizado.";
}
}
答案 0 :(得分:0)
您可能应该能够使用上传文件的文件路径作为fopen
- $_FILES['file']['tmp_name']
的源代码 - 尽管它未经过测试。除非您还需要保存上传的csv文件,否则不需要像通常使用文件上传那样使用move_uploaded_file
。
强制性的&#34;不使用mysql_*
功能&#34; - 它们已被弃用,并且不提供针对sql注入的保护。最好使用mysqli
或PDO
,以便您可以利用prepared statements
<?php
/* logic tests to ensure there is data present */
if( isset( $_POST['submit'], $_FILES['file'] ) ) {
/* assign the tmp_name of the uploaded file to a variable */
$tmp = $_FILES['file']['tmp_name'];
/* open a file handle on the temp file */
$handle = fopen( $tmp, "r" );
$i=0;
if ( !$handle ) {
echo "<p> Arquivo não encontrado! </p>";
} else {
/* only open db connection if there are no problems */
$conexao = mysql_connect ("localhost", "root", "") or die ( mysql_error() );
$bd = mysql_select_db ("wcfleet_demo");
while ( $valores = fgetcsv( $handle, 100000, ";" )!== false ) {
$lines = file( $msg );
if( $i >= 8 ) {
$line = explode ( ';', $lines[$i]);
$sql = "INSERT INTO via_verde (identificador, matricula, referencia, data_entrada, hora_entrada, entrada, data_saida,
hora_saida, saida, valor, valor_desconto, taxa_iva, operador, servico, data_pagamento, cartao_n)
VALUES ('$line[0]', '$line[1]', '$line[2]', '$line[3]', '$line[4]', '$line[5]', '$line[6]', '$line[7]',
'$line[8]', '$line[9]', '$line[10]', '$line[11]', '$line[12]', '$line[13]', '$line[14]', '$line[15]')";
mysql_query( $sql ) or die ( mysql_error() );
}
$i++;
}
fclose( $handle );
mysql_close( $conexao );
/* delete the temp file */
@unlink( $tmp );
echo "Processo finalizado.";
}
}
?>