Code php import dữ liệu từ excel (xml) vào SQL

Thảo luận trong 'Source code' bắt đầu bởi hongoctrien, 17 Tháng bảy 2011.

  1. Offline

    hongoctrien

    • Friends

    Số bài viết:
    2.449
    Đã được thích:
    2.464
    Điểm thành tích:
    2.431
    Chuẩn bị test code
    - Tạo database test
    - Tạo table users gồm 3 feld

    Mã:
    CREATE TABLE  `test`.`users` (
    `fist_name` VARCHAR( 100 ) NOT NULL ,
    `last_name` VARCHAR( 100 ) NOT NULL ,
    `age` INT NOT NULL
    ) ENGINE = MYISAM ;
    Code import:

    Mã:
    <?php
    $page_title = "Import excel to sql";
    $line = 0;
    $them = 0;
    //Cau lenh ket noi
    $con = mysql_connect("localhost","root","");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("test", $con);
    //Code lay du lieu tu excel
    	$data = array();  
    	if ( $_FILES['ufile']['tmp_name'])  
    	{  
    	    $dom = DOMDocument::load( $_FILES['ufile']['tmp_name'] );  
    	    $rows = $dom->getElementsByTagName( 'Row' );  
    		$tde = array();
    		foreach ( $rows as $row)
    		{ 
    		$cells = $row->getElementsByTagName( 'Cell' );  
    		$datarow = array();  
    			foreach ( $cells as $cell )
    			{  
    	     		if ( $line == 0 )
    	     		{
    	        		$tde[] = $cell->nodeValue;
    	     		}
    	     		else
    	     		{
    	     			$datarow [] = $cell->nodeValue;
    	     		} 
    		 	}  
    		$data [] = $datarow;  
    		$line = $line + 1;      
    		}
    //
    	foreach( $data as $row ) 
    	{  
    		$imp = array();
    		$i = 0;
    		if (isset( $row[0] ) )
    		{
    		foreach( $row as $item ) 
    		{
    		//chen vo CSDL
    			$imp[$i] = $item;
    			$i = $i + 1;	
    		} 
    		
    		if ( !$numrows )
    		{
    	   	$sql = "INSERT INTO `users` (`fist_name`, `last_name`, `age`) VALUES ('". $imp[0] ."', '". $imp[1] ."','". $imp[2] ."')";
    		$them = $them + 1;
    		}
    		if (!mysql_query($sql,$con))
    		{
    		die('Error: ' . mysql_error());
    		}
    		$added=$them;
    		}
    		}  
    	}
    
    echo "<div><form enctype=\"multipart/form-data\" id=\"form\" name=\"form\" method=\"post\">";
    echo "<center><table border=\"1\">";
    echo "	<tr>";
    echo "		<td class=\"fr\" width=\"200\">Chon duong dan den file xml</td>";
    echo "		<td><input type=\"file\" name=\"ufile\" size = \"35\" id=\"ufile\"/>";
    echo "		<input type=\"submit\" name=\"import\" id=\"import\" value=\"Import\" /></td>";
    echo "	</tr>";
    echo "	</table></center>";
    echo "	</form>";
    echo "</div>";
    if ($them>0)
    echo "<center><br>Co $added hang duoc chen vao thanh cong</center>";
    ?>
    Dựa vào code này có thể tùy biến thêm nhiều kiểu chèn dữ liệu.

Chia sẻ trang này

Advertising: Linux system admin | nukeviet | nukeviet 4 | Upload ảnh miễn phí