2016-09-27 6 views
1

저는 PHP를 배우고 있으며, 파일 처리와 관련된 작은 프로젝트를 시작했습니다. 숫자에 대한 데이터베이스 검사기 (간단한 유지)입니다. 그 말은 숫자를 입력하고 제출 버튼을 누르면 PHP가 텍스트 파일을 검색하여 번호로 이름을 얻는 것입니다.숫자가 가진 자릿수가 1보다 큰 경우 더 많이 검색하십시오.

텍스트 파일은 다음과 같습니다
1 산드라
2 피에트에게
3 프랜시스을
등 ...

코드 : 그래서

<?php 
    // Type your code here 
    $val = $row = NULL; 


    if (isset($_POST["submit"])) { 
     $myFile = fopen("testData.txt","r"); 
     $number = $_POST["input"]; 
     $cntNumber = strlen($number); 



     while (!feof($myFile)){ 
      $val = fgetc($myFile); 

      if (is_numeric($val)) { 
       if ($cntNumber > 1) { 
        // Point where I Don't know what to do 
       } elseif ($val == $number) { 
        $row = fgets($myFile); 
       } 

      } 
     } 
    } 

    ?> 

    <div style="width: 232px; height: 100px; border: 1px solid gray; margin-bottom: 5px;"> 
     <?php 
      echo $row . "<br>";  
     ?> 
    </div> 
    <form action="index.php" method="post"> 
     <input name="input" placeholder="Number" type="text"> 
     <input name="submit" value="Search" type="submit"> 
    </form> 

수는 하나 이상있는 경우 숫자는 다음 일치하는 숫자를 검색해야하지만 어떻게 달성 할 수 있는지 알 수 없습니다. 나는 나의 설명이 충분히 명확했으면 좋겠다. 어떤 질문을해도 상관 없다. 사전에

감사

+0

정말, 데이터베이스를 사용해야합니다. –

+0

나는 곧 거기에 갈 것이지만, 지금은 텍스트 파일을 고수 할 것입니다. – FlyingUnderpants

답변

2

난 당신이 f - 파일 기능을 사용할지 여부를 알 수는 없지만, 더 간단 솔루션입니다 :

if (isset($_POST["submit"])) { 
    $myFile = file("testData.txt"); 
    // print_r $myFile and see that this is array of lines 

    $number = $_POST["input"]; 
    // iterate over your lines: 
    foreach ($myFile as $line) { 
     // as each line contains two values divided by a space, 
     // you can explode the line into two parts 
     $parts = explode(' ', $line); 
     // print_r($parts) to see result 

     // next check first part which is number: 
     if ($parts[0] == $number) { 
      echo 'Found!'; 
      break; // exit loop as your value is found 
     } 
    } 
} 

당신이 다음 코드 수 f - 파일 기능을 사용하려면 :

$fh = fopen("testData.txt", "r"); 
while(!feof($fh)) { 
    $str = fgets($fh, 1024); 
    $parts = explode(' ', $str); 
    // print_r($parts) to see result 
    if ($parts[0] == $number) { 
     echo 'Found!' . $str; 
     break; // exit loop as your value is found 
    } 
} 

그러나 데이터베이스를 저장소로 사용하는 것이 좋습니다.

+0

고맙습니다. @u_mulder! 나는 네가하는 말을 듣고 곧 데이터베이스에 갈 수 있기를 희망한다. 그러나 그 당시 한 가지.) – FlyingUnderpants

관련 문제