2012-11-28 2 views
0

mysql scv 테이블을 업데이트하기 위해 csv 파일을 사용하고 싶습니다. 코드 작성 방법? 나는이 일을하는 경험이 없다.csv 파일을 업로드하고 mysql db를 업데이트하는 방법은 무엇입니까?

<p>please select a scv file to upload</p> 
<form action="index.php" method="post"> 
    <input type="file" name="scv" /> 
    <input type="submit" value="submit" /> 
</form> 
<?php 
    mysql_connect('localhost','root','admin'); 
    mysql_select_db('linjuming'); 
    // how to upload a scv file and insert or update the "csv" table? 

?> 

enter image description here

+0

가능한 복제본 [PHP/MYSQL 업로드, mysql-process-table 디자인으로 .csv 파일 가져 오기] (http://stackoverflow.com/questions/10657204/php-mysql-upload-import-csv-file-to) -mysql-process-table-design) – Kermit

+0

[** 새 코드에서 mysql_ * 함수를 사용하지 마십시오.] (http://bit.ly/phpmsql). 그들은 더 이상 유지 관리되지 않으며 [비추천 프로세스] (http://j.mp/Rj2iVR)가 시작되었습니다. [** 빨간색 상자 **] (http://j.mp/Te9zIL)를 참조하십시오. 대신 [* prepared statements *] (http://j.mp/T9hLWi)에 대해 알아보고 [PDO] (http://php.net/pdo) 또는 [MySQLi] (http://php.net/)를 사용하십시오. mysqli) - [이 기사] (http://j.mp/QEx8IB)는 어떤 결정을 내리는 데 도움이 될 것입니다. PDO를 선택하면 [여기는 좋은 튜토리얼입니다] (http://j.mp/PoWehJ). –

답변

1

업로드 파일 :

<form action="upload_target.php" method="post" enctype="multipart/form-data"> 
<label for="file">Filename:</label> 
<input type="file" name="file" id="file"><br> 
<input type="submit" name="submit" value="Submit"> 
</form> 

귀하의 upload_target.php

$ 내선 =의 PathInfo ($ _ FILES [ '파일'] [ ' 이름 '], PATHINFO_EXTENSION);

if ($ext == "csv" && $_FILES["file"]["error"] == 0) 
{ 
    $target = "upload/" . $_FILES["file"]["name"]; 
    move_uploaded_file($_FILES["file"]["tmp_name"], $target); 

    if (($handle = fopen($target, "r")) !== FALSE) 
    { 
     while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) 
     { 
      print_r($data); 
     } 

     fclose($handle); 
    } 
} 

매우 기본적이고 매우 적은 수표/유효성 검사가 있습니다. print_r($data)에는 이제 데이터베이스에 삽입 할 수있는 CSV의 한 줄이 들어 있습니다.

그러나 PHP의 MySQL 기능은 향후 제공되지 않을 예정이므로 PDO 또는 MySQLi를 사용하는 것이 좋습니다.

1

이의 여러 부분을있다 :

먼저 다음과 같이 양식은에 enctype 세트가 있어야합니다

<form enctype="multipart/form-data" action="index.php" method="post"> 

를 그렇지 않으면 파일 업로드를 허용하지 않습니다, .

이 작업을 완료하면 $_FILES 변수를 사용하여 파일에 액세스 할 수 있습니다. 파일을 업로드 한 후, 다음과 같이 액세스 할 수 있습니다 :

if (isset($_FILES["scv"])) { 
    $file = $_FILES["scv"]; 
    $file_name = $file["name"]; 
    $ext = pathinfo($file_name, PATHINFO_EXTENSION); 
    if ($ext!="CSV" && $ext!="TXT") { 
     die('The file must be csv or txt format.'); 
    } 
    $saveto_path_and_name = '/path/to/file.csv'; // Where you want to save the file 
    move_uploaded_file($file["tmp_name"], $saveto_path_and_name); 
} 

을 파일을 저장 한 후에는 다음을 열고 가져올 수 있습니다. 즉 할 사소한 아니지만, 여기에 몇 가지 프라이머 코드입니다 :

// Open the file for reading 
$handle = @fopen($saveto_path_and_name, "r") or die(__("Unable to open uploaded file!", "inventory")); 
// Grab the first row to do some checks 
$row = fgets($inv_file, 4096); 
// See if it's comma or tab delimited 
if (stripos($inv_row, "\t")) { 
    $sep = "\t"; 
} else { 
    $sep = ","; 
} 

while (! feof($handle)) { 
    $rowcount = 0; 
    // Get the individual fields 
    $inv_fields = explode($sep, $inv_row); 
    $fields = array(); 
    // Iterate through the fields to do any sanitization, etc. 
    foreach ($inv_fields as $field) { 
     // Highly recommended to sanitize the variable $field here.... 
     $fields[] = $field; 
     $rowcount++; 
} 
    // This is where you would write your query statement to insert the data 
    // This is just EXAMPLE code. Use the DB access of your choice (PDO, MySQLi) 
    $sql = vsprintf('INSERT INTO `table` (`column`, `column2`, ...) VALUES (%s, %d, ...)', $fields); 
    // Get the next row of data from the file 
    $row = fgets($inv_file, 4096); 
} 
관련 문제