2014-12-09 2 views
0

기본 키가있는 PHP 코드를 사용하여 MySQL 데이터베이스에 데이터를 가져 오거나 업로드하는 방법을 알고 싶습니다. PHP의 타임 스탬프 기능을 사용하여 생성됩니다. 도와주세요. 또한 각 제품의 기본 키 값과 이름이 같은 이미지를 업로드하십시오. 는PHP를 사용하여 MySQL 데이터베이스에서 파일을 Excel로 가져 오는 방법은 무엇입니까?

+0

시도한 내용을 알려주십시오. – Pupil

+1

우리는 당신의 집안 일을 위해 여기 있지 않습니까 ?? 적어도 약간의 노력을 보여줍니다. – Manwal

답변

0
**example for import excel or csv file to mysql database with very easy method. 
query:** 

- CREATE TABLE IF NOT EXISTS `studentdata`( `StudentID` int(11) NOT 
    NULL AUTO_INCREMENT, `FirstName` varchar(30) NOT NULL, `LastName` 
    varchar(30) NOT NULL, `MobileNo` varchar(30) NOT NULL, `City` 
    varchar(30) NOT NULL, PRIMARY KEY (`StudentID`)) E 

NGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1; 

php 

if(isset($_POST['submit'])) 
{ 
    if($_FILES['csvFile']['name']!="") 
    { $fileName=uploadFile($_FILES['excelFile'],array(".csv"),"excel_file"); 
     $row=0; 
     if(($handle = fopen("excel/".$fileName , "r")) !== FALSE) 
     { 
      while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
      { 
       $num = count($data); 
       $query="INSERT INTO StudentData(FirstName,LastName,MobileNo,City) 
           VALUES('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."')"; 
       mysql_query($query); 
      } 
      fclose($handle); 
     } 
    } 
    else if($_FILES['excelFile']['name']!="") 
    { 
     $fileName=uploadFile($_FILES['excelFile'],array(".xls",".xlsx"),"excel_file"); 
     $data = new Spreadsheet_Excel_Reader(); 
     $data->read('excel_file/'.$fileName); 
     for($i=1;$i<=$data->sheets[0]['numRows'];$i++) 
     { 
      $firstname=$data->sheets[0]['cells'][$i][1]; 
      $lastname=$data->sheets[0]['cells'][$i][2]; 
      $mobile=$data->sheets[0]['cells'][$i][3]; 
      $city=$data->sheets[0]['cells'][$i][4]; 
      $query="INSERT INTO StudentData(FirstName,LastName,MobileNo,City) 
         VALUES('".$firstname."','".$lastname."','".$mobile."','".$city."')"; 
      mysql_query($query); 
     } 
    } 
} 
+0

귀하의 노력에 감사드립니다. 그러나 튜토리얼 사이트가 아닙니다. 환영합니다 스택 – Manwal

+0

이것은 설명이없는 코드 덤프이며 타사 라이브러리가 필요하며이를 설정하거나 사용하는 데 대한 설명이 없습니다. – siride

0

두 개의 파일을 확인 감사합니다의 index.php를 (MySQL 데이터베이스에 데이터를 가져 오기위한)와 import.php (업로드 양식을 표시). 또한 타임 스탬프에 포함 된 시간은 다음과 같습니다. Index.php 코드 :

<?php 
$uploadedStatus = 0; 
if (isset($_POST["submit"])) { 
if (isset($_FILES["file"])) { 
//if there was an error uploading the file 
if ($_FILES["file"]["error"] > 0) { 
echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; 
} 
else { 
if (file_exists($_FILES["file"]["name"])) { 
unlink($_FILES["file"]["name"]); 
} 
$storagename = "file1.xlsx"; 
move_uploaded_file($_FILES["file"]["tmp_name"], $storagename); 
$uploadedStatus = 1; 
} 
} else { 
echo "No file selected <br />"; 
} 
} 


<table width="600" style="margin:115px auto; background:#f8f8f8; border:1px solid #eee; padding:20px 0 25px 0;"> 
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data"> 
<tr><td colspan="2" style="font:bold 21px arial; text-align:center; border-bottom:1px solid #eee; padding:5px 0 10px 0;"> 
<a href="http://www.website.com" target="_blank">website.com</a></td></tr> 
<tr><td colspan="2" style="font:bold 15px arial; text-align:center; padding:0 0 5px 0;">Browse and Upload Your File </td></tr> 
<tr> 
<td width="50%" style="font:bold 12px tahoma, arial, sans-serif; text-align:right; border-bottom:1px solid #eee; padding:5px 10px 5px 0px; border-right:1px solid #eee;">Select file</td> 
<td width="50%" style="border-bottom:1px solid #eee; padding:5px;"><input type="file" name="file" id="file" /></td> 
</tr> 
<tr> 
<td style="font:bold 12px tahoma, arial, sans-serif; text-align:right; padding:5px 10px 5px 0px; border-right:1px solid #eee;">Submit</td> 
<td width="50%" style=" padding:5px;"><input type="submit" name="submit" /></td> 
</tr> 
</table> 
?> 

<?php 
/************************ YOUR DATABASE CONNECTION START HERE ****************************/ 

define ("DB_HOST", "localhost"); // set database host 
define ("DB_USER", ""); // set database user 
define ("DB_PASS",""); // set database password 
define ("DB_NAME",""); // set database name 

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection."); 
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database"); 

$databasetable = "YOUR_TABLE"; 

/************************ YOUR DATABASE CONNECTION END HERE ****************************/ 


set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/'); 
include 'PHPExcel/IOFactory.php'; 

// This is the file path to be uploaded. 
$inputFileName = 'file1.xlsx'; 

try { 
    $objPHPExcel = PHPExcel_IOFactory::load($inputFileName); 
} catch(Exception $e) { 
    die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage()); 
} 

$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true); 
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet 

for($i=2;$i<=$arrayCount;$i++){ 
$userName = trim($allDataInSheet[$i]["A"]); 
$userMobile = trim($allDataInSheet[$i]["B"]); 

$query = "SELECT name FROM YOUR_TABLE WHERE name = '".$userName."' and email = '".$userMobile."'"; 
$sql = mysql_query($query); 
$recResult = mysql_fetch_array($sql); 
$existName = $recResult["name"]; 
if($existName=="") { 
$insertTable= mysql_query("insert into YOUR_TABLE (name, email, addedon) values('".$userName."', '".$userMobile."', '".now()."');"); 

$msg = 'Record has been added. <div style="Padding:20px 0 0 0;"><a href="http://website.com/uploaded.htm" target="_blank">Go Back to mainpage</a></div>'; 
} else { 
$msg = 'Record already exist. <div style="Padding:20px 0 0 0;"><a href="http://website.com/already.htm" target="_blank">Go Back to tutorial</a></div>'; 
} 
} 
echo "<div style='font: bold 18px arial,verdana;padding: 45px 0 0 500px;'>".$msg."</div>"; 

?> 
+0

mysql_ * 함수를 사용하지 마십시오. 그들은 비난 받고 사악 해. – siride

관련 문제