2012-06-28 4 views
1

이상한 문제가 있습니다. MySQL 데이터베이스에 데이터를 삽입하는 PHP 코드가있는 HTML 페이지가 있습니다. 데이터는 오류없이 잘못된 순서로 DB에 저장됩니다.레코드가 오름차순으로 삽입되지 않음

다음은 스크린 샷입니다. 오른쪽 테이블에는 기존 레코드가 표시됩니다. 처음 2 개의 레코드가 올바르게 표시됩니다. enter image description here 그러나 더 많은 레코드를 저장하면 다음과 같이 표시됩니다. enter image description here enter image description here

심지어 MySQL 테이블에서도 레코드가 삽입됩니다.

enter image description here

나는 문제가 그래서 아래의 페이지에 대한 전체 코드를 표시 한 곳에 정확히 모르겠어요. 각 코드 블록이 수행하는 작업에 대해 주석을 달았습니다. 뭔가 명확히하기 위해 나를 필요로한다면 의견을 말하십시오.

위치 ID은 자동 생성 코드입니다.

<html> 
<head> 
<script language="javascript"> 
function SelectAll(source) 
{ //The code for the 'Select All' checkbox 
    checkboxes = document.getElementsByTagName("input"); 
    for(var i in checkboxes) 
    { 
     if(checkboxes[i].type == 'checkbox') 
     { 
      checkboxes[i].checked = source.checked; 
     } 
    } 
} 
</script> 
</head> 
<body> 

<?php 
//Database connection initialization 
require_once("db_handler.php"); 

$conn = iniCon(); 
$db = selectDB($conn); 

/* Generating the new Location ID */ 
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1"; 
$result = mysql_query($query, $conn); 
$row = mysql_fetch_array($result); 
$last_id = $row['LID']; 

$id_letter = substr($last_id, 0, 1); 
$id_num = substr($last_id, 1) + 1; 
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT); 
//$id_num = sprintf("%03d", $id_num); 
$new_id = $id_letter . $id_num; 

/* Displaying the exsisting locations */   
$query = "SELECT * FROM locations"; 
$result = mysql_query($query, $conn); 

$count = mysql_num_rows($result); 

?> 

<! The table which displays the existing records > 
<div id="display"> 
<b>Locations</b><br/><br/> 
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" > 
<table border="1"> 
    <tr> 
     <th>Location ID</th> 
     <th>Code</th> 
     <th>Location</th> 
     <th><i>Delete</i></th> 
    </tr> 
    <?php 
    while($row = mysql_fetch_array($result)) 
    { 
    ?> 
    <tr> 
     <td align="center"><? echo $row["LID"]; ?></td> 
     <td align="center"><? echo $row["Code"]; ?></td> 
     <td><? echo $row["Location"]; ?></td> 
     <td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td> 
    </tr> 
    <?php 
    } 
    ?> 
</table> 

<br/> 
    <div id="buttons2"> 
      <input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" /> 
    </div> 
</form> 
</div> 

<! New record saving area > 
<b id="loc_caption_1">Enter a new location</b> 
<div id="loca"> 
    <form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" > 
     <table width="300" border="0"> 
      <tr> 
      <td>Location ID</td> 
      <td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td> 
      </tr> 
      <tr> 
      <td>Code</td> 
      <td><input type="text" name="code" style="text-align:right" /></td> 
      </tr> 
      <tr> 
      <td>Location</td> 
      <td><input type="text" name="loc" style="text-align:right" /></td> 
      </tr> 
     </table> 
</div> 
<br/> 
<div id="buttons"> 
    <input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" /> 
</div> 
    </form> 

<?php 
//Saving record 
if(isset($_POST["savebtn"])) 
{ 
    $id = $_POST["lid"]; 
    $code = $_POST["code"]; 
    $location = $_POST["loc"]; 

    $query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')"; 
    $result = mysql_query($query, $conn); 

    if (!$result) 
    { 
     die("Error " . mysql_error()); 
    } 
    else 
    { 
     echo "<br/><br/>"; 
     echo "<strong>1 record added successfully!</strong>"; 
     echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">"; 
    } 

    mysql_close($conn); 
} 

//Deleting selected records 
if(isset($_POST["deletebtn"])) 
{ 
    for($i = 0; $i < $count; $i++) 
    { 
     $del_id = $_POST["checkbox"][$i]; 
     $query = "DELETE FROM locations WHERE LID = '$del_id' "; 
     $result = mysql_query($query, $conn); 
    } 

    if (!$result) 
    { 
     die("Error " . mysql_error()); 
    } 
    else 
    { 
     echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">"; 
    } 

    mysql_close($conn); 
} 

?> 

</body> 
</html> 

누구든지이 문제의 원인과 해결 방법을 알려주십시오.

감사합니다.

+0

SELECT 문에 ORDER BY 절을 추가 하시겠습니까? – andrewsi

+1

레코드가 어떤 순서로도 삽입되지 않습니다. 레코드는 단순히 존재합니다. 주문은 검색어에 적용됩니다. 또한 위치 ID를 생성하는 방식이 잘못되었습니다. 마지막 레코드를 쿼리하는 대신 자동 증가 열을 사용해야합니다. –

+2

레코드 삽입 순서를 보장 할 수 없습니다. 테이블 *에서 데이터의 순서는 중요하지 않습니다. 어떤 것을 출력으로 정렬하려면, 해당 SELECT 문에 ORDER BY 절을 붙이십시오. –

답변

6

데이터베이스의 레코드는 특별한 순서없이 데이터베이스에 저장됩니다 (순서는 정해지지 만 엔진을 결정할 때까지입니다). 결과를 특정 순서로 가져 오려면 데이터를 쿼리 할 때 명시 적으로 지정해야합니다. 귀하의 경우 다음과 같이 변경하십시오.

/* Displaying the exsisting locations */   
$query = "SELECT * FROM locations ORDER BY lid"; 
$result = mysql_query($query, $conn); 
+0

를 본다. ID에 대해이 자동 생성 기능을 구현할 때만 시작되기 때문에 나는 의문의 여지가있었습니다. 그 전에는 데이터베이스 테이블에서도 괜찮 았습니다. 지금은 이해. 'ORDER BY' 절을 추가하면 표시 문제가 해결되었습니다. 고맙습니다. – Isuru

관련 문제