我有一个按 ASC 顺序对名称进行排序的表格,但是当我单击该按钮时它不起作用。 我试着用 2 个按钮做同样的事情,并检查了一些可用的代码,但它根本不起作用。有帮助吗?
PHP 代码:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myfeeds";
$conn = mysql_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed");
}
$db = mysql_select_db("myfeeds", $conn);
if (!$db) {
die("Can't select database");
}
if (isset($_POST['asc'])) {
$result = mysql_query("SELECT * FROM websites ORDER BY name ASC");
} else {
$result = mysql_query("SELECT * FROM websites ORDER BY name DESC");
}
if (!$result) {
die("Failed to show queries from table");
}
$num = mysql_numrows($result);
mysql_close();
?>
这是按钮:
SORT BY:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<button type="submit" id="asc" name="asc">ASC</button>
</form>
表格:
<table cellpadding="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>URL</th>
<th>Description</th>
<th>Logo</th>
</tr>
<?php
$i = 0;
while ($i < $num) {
$f5 = mysql_result($result, $i, "id");
$f1 = mysql_result($result, $i, "name");
$f2 = mysql_result($result, $i, "url");
$f3 = mysql_result($result, $i, "description");
$f4 = mysql_result($result, $i, "image");
?>
<tr>
<td><?php echo $f5; ?></td>
<td><?php echo $f1; ?></td>
<td><?php echo $f2; ?></td>
<td><?php echo $f3; ?></td>
<td><?php echo "<img src='$f4'>"; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
最佳答案
根据manual ,mysql_connect
的第四个参数应该是一个新的连接链接,不是数据库名。
new_link
If a second call is made to
mysql_connect()
with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. >The new_link parameter modifies this behavior and makesmysql_connect()
always open a new link, even ifmysql_connect()
was called before with the same parameters. In SQL safe mode, this parameter is ignored.
我建议改用 mysqli_*
,因为 mysql 已被弃用。
当然,不要忘记在查询后获取行。
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myfeeds";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$order = isset($_POST['asc']) ? 'ASC' : 'DESC';
$sql = "SELECT * FROM websites ORDER BY name $order";
$query = mysqli_query($conn, $sql);
$num = $query->num_rows;
if($num > 0) {
while($row = mysqli_fetch_assoc($query)) {
echo $row['name'] . '<br/>';
}
}
关于php - 使用 PHP 对 MYSQL 表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27085580/