按列对表中的数据进行排序

时间:2012-12-11 10:33:44

标签: php mysql

我想在html表的标题中克隆时从mysql数据库中对数据进行排序。我写了这段代码:

$username = $_SESSION['username']; // gets the username

echo "<table class='normal_table'>";

$new_word = mysql_query("SELECT * FROM new_word WHERE username='$username'");
$new_word2 = mysql_query($new_word);

echo " 

<tr>
<th><a href='test.php?sort=cz'>Czech:</a></th>
<th><a href='test.php?sort=en'>English:</a></th>
<tr>";

if ($_GET['sort'] == 'cz')
{
 $new_word .= " ORDER BY cz";
}
elseif ($_GET['sort'] == 'en')
{
 $new_word .= " ORDER BY en";
}

while($new_word2 = mysql_fetch_array($new_word)){

echo "
<tr>
<td> ".$new_word2['cz']."</td>
<td>".$new_word2['en']."</td>
</tr>

"; }

echo "</table>";

但是在屏幕上没有出现任何数据:(我做错了什么?

2 个答案:

答案 0 :(得分:2)

您正在

执行查询
$new_word = mysql_query("SELECT * FROM new_word WHERE username='$username'");

然后尝试在

处附加到该查询对象
$new_word .= " ORDER BY en";

您需要先构建查询字符串

所以

$sql =  "SELECT * FROM new_word WHERE username='$username'"

附加您的ORDER BY

$sql .= " ORDER BY en";

然后执行

$new_word = mysql_query($sql);

编辑:同时删除$new_word2 = mysql_query($new_word);并更改您的时间以使用$new_world,因为Uttam Kadam在answer

中说

答案 1 :(得分:1)

$new_word2 = mysql_query($new_word); //$new_word wrong

删除此行是额外的。