如何添加按钮或对数据进行排序的链接?

时间:2012-01-27 10:36:52

标签: php sqlite group-by sql-order-by

在下面的代码中,如何添加按“名称”对数据进行排序的按钮或链接?

以下代码只是一个示例,是我从http://fwebde.com/php/sqlite-php/找到的修改后的代码版本。代码的结构非常有趣,我想用sort-element来改进它。

谢谢!

<?php
$db = new PDO('sqlite:db.db');
if (isset($_POST['name']) && isset($_POST['message'])) {
try {
    $stmt = $db->prepare("INSERT INTO messages (name, message) VALUES (:name, :message);");
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':message', $message);

    $title = $_POST['name'];
    $content = $_POST['message'];
    $stmt->execute();
} catch (Exception $e) {
    die ($e);
}
}try {
$posts = $db->prepare('SELECT * FROM messages;');
$posts->execute();
} catch (Exception $e) {
die ($e);
}

?>

<?php while ($post = $messages->fetchObject()): ?> 
 <?php echo $post->name ?>
 <?php echo $post->message ?>
<?php endwhile; ?>

<form action="" method="post">
    <label for="name">Name:</label>
    <input type="text" name="name" />
    <textarea name="message" rows="8" cols="50"></textarea>
    <input type="submit" name="submit" value="Submit" />
</form>

1 个答案:

答案 0 :(得分:0)

<?php
    $db = new PDO('sqlite:db.db');
    if (isset($_POST['submit']) && isset($_POST['name']) && isset($_POST['message'])) {
    try {
     //Insert data
    } catch (Exception $e) {
        die ($e);
    }
    }
    try {
        $order = "";
        if(isset($_POST['sort'])){
            $order = " ORDER BY `name`"; // Order list by name
            $orderFlag = 1;
            if(isset($_POST['order']) && $_POST['order'] == 1){
                 $order .= " DESC";
                 $orderFlag = 0;
            }

         }
        $posts = $db->prepare("SELECT * FROM `messages`" . $order  . ";");
        $posts->execute();
    } catch (Exception $e) {
        die ($e);
    }

    ?>

    <?php while ($post = $posts ->fetchObject()): ?> 
     <?php echo $post->name ?><?php echo $post->message ?><br/>
    <?php endwhile; ?>

    <form action="" method="post">
        <!--pushing this button sort by name -->
        <input type="submit" name="sort" value="Sort by name" />
        <input type="hidden" name="order" value="<?=$orderFlag?>" />

        <label for="name">Name:</label>
        <input type="text" name="name" />
        <textarea name="message" rows="8" cols="50"></textarea>
        <!--pushing this button insert new data -->
        <input type="submit" name="submit" value="Submit" />
    </form>