2011-02-27 3 views
2
<?php 
$con = mysql_connect ("localhost", "user", "pass") 
    or die ('Error: ' . mysql_error()); 
mysql_select_db ("members"); 

if(isset($_GET['orderby'])){ 
$order = $_GET['orderby']; 
$result = "SELECT * FROM persons ORDER BY ".mysql_real_escape_string($order)." DESC"; 
} 
else{ 
$result = mysql_query("select * from persons"); 
} 

$num_rows = mysql_num_rows($result); 
$row_counter = 0; 

echo "<table width=600 border=0 cellspacing=0>\n"; 
echo "<tr>\n 
     <th>&nbsp;</th>\n 
     <th>First Name</th>\n 
     <th>Last Name</th>\n 
     <th>Email Address</th>\n 
     <th>City</th>\n 
     <th>State</th>\n 
     <th><a href='index.php?orderby=submitDate'>Date</a></th>\n 
     </tr>"; 

while($row = mysql_fetch_array($result)){ 
    if($row_counter % 2){ 
    $row_color="bgcolor='#FFFFFF'"; 
    } 
    else{ 
    $row_color="bgcolor='#F3F6F8'"; 
    } 
    echo "<tr ".$row_color.">"; 
    echo "<td class='id'>" . $row['id'] . "</td>\n"; 
    echo "<td>" . $row['firstName'] . "</td>\n"; 
    echo "<td>" . $row['lastName'] . "</td>\n"; 
    echo "<td>" . $row['email'] . "</td>\n"; 
    echo "<td>" . $row['city'] . "</td>\n"; 
    echo "<td>" . $row['state'] . "</td>\n"; 
    echo "<td>" . $row['submitDate'] . "</td>\n"; 
    echo "</tr>"; 
    $row_counter++; 
    } 
echo "</table>"; 

mysql_close($con); 
? 

>링크는 PHP MySQL의 테이블 열을 정렬하려면

난 그냥 내 링크 내 쿼리가 작동하지 않는 정렬하는 이유를 알아낼 수 없습니다. 어떤 아이디어? 사전 감사합니다!

+1

이 코드는 SQL 주입이 심하게 어려움에 유의하십시오. –

답변

2

if else 블록이 잘못되었습니다. 한 경우 $ 결과는 다른 결과 집합 인 결과 집합입니다. 아래의 코드를 확인하십시오.

<?php 
$con = mysql_connect ("localhost", "user", "pass") 
    or die ('Error: ' . mysql_error()); 
mysql_select_db ("members"); 

if(isset($_GET['orderby'])){ 
$order = $_GET['orderby']; 
$sql = "SELECT * FROM persons ORDER BY ".mysql_real_escape_string($order)." DESC"; 
} 
else{ 
$sql = "select * from persons"; 
} 
$result = mysql_query($sql); 
$num_rows = mysql_num_rows($result); 
$row_counter = 0; 

echo "<table width=600 border=0 cellspacing=0>\n"; 
echo "<tr>\n 
     <th>&nbsp;</th>\n 
     <th>First Name</th>\n 
     <th>Last Name</th>\n 
     <th>Email Address</th>\n 
     <th>City</th>\n 
     <th>State</th>\n 
     <th><a href='index.php?orderby=submitDate'>Date</a></th>\n 
     </tr>"; 

while($row = mysql_fetch_array($result)){ 
    if($row_counter % 2){ 
    $row_color="bgcolor='#FFFFFF'"; 
    } 
    else{ 
    $row_color="bgcolor='#F3F6F8'"; 
    } 
    echo "<tr ".$row_color.">"; 
    echo "<td class='id'>" . $row['id'] . "</td>\n"; 
    echo "<td>" . $row['firstName'] . "</td>\n"; 
    echo "<td>" . $row['lastName'] . "</td>\n"; 
    echo "<td>" . $row['email'] . "</td>\n"; 
    echo "<td>" . $row['city'] . "</td>\n"; 
    echo "<td>" . $row['state'] . "</td>\n"; 
    echo "<td>" . $row['submitDate'] . "</td>\n"; 
    echo "</tr>"; 
    $row_counter++; 
    } 
echo "</table>"; 

mysql_close($con); 
?> 
+1

!! 고맙습니다 !! 나는 당신이 말할 수있는 초심자이다 : 나는 그것을 많이 고맙다! – Jason