使用单选按钮过滤数据

时间:2016-07-30 15:33:23

标签: php html mysql css

我想尝试在我的网页上添加两个过滤器。

  • 一个日期过滤器和另一个颜色过滤器。
  • 如果未设置过滤器,则应显示所有记录。

我正在尝试使用if / else语句以及名称/值对。

谁能看到我做错了什么?我尝试了几件事,这就是我最终的结果。我也阅读了很多页面并尝试使用这些例子,但似乎没有什么对我有用。 Stackoverflow link Stackoverflow link

HTML / PHP

<?php
//connect to the database
$dbc = mysqli_connect('host', 'user', 'password', 'cars') or die('Error connecting to MySQL Server.');

//If RadioButton Clicked Sort the Database by dateadded Asc / Desc
if(isset($_POST['dateorder'])){
        if($_POST['dateorder'] == 'dateasc'){
             //Run query for dateasc
             $query = "SELECT * FROM cardetails ORDER BY caradded asc";
        }elseif($_POST['dateorder'] == 'datedesc'){
             //Run query for datedesc
             $query = "SELECT * FROM cardetails ORDER BY caradded desc";
        }
}else{
        $query = "SELECT * FROM cardetails ORDER BY id asc";
}

//If RadioButton Clicked Sort the Database by Color Red, Green, Blue
if(isset($_POST['color'])){
        if($_POST['color'] == 'red'){
             //Run query for red color
             $query = "SELECT * FROM cardetails WHERE color = 'red'";
        }elseif($_POST['color'] == 'green'){
             //Run query for green color
             $query = "SELECT * FROM cardetails WHERE color = 'green'";
        }elseif($_POST['color'] == 'blue'){
             //Run query for blue color
             $query = "SELECT * FROM cardetails WHERE color = 'blue'";
        }
}else{
     $query = "SELECT * FROM cardetails ORDER BY id asc";
}


$result = mysqli_query($dbc, $query) or die('Error Refreshing the page: ' . mysqli_error($dbc));

//Retrieve the practice tasks from the database table
$result = mysqli_query($dbc, $query) or die('Error querying database.');

//start pagination
//Get the total count of rows.
$sql = "SELECT COUNT(id) FROM cardetails";
$query = mysqli_query($dbc, $sql);
$row = mysqli_fetch_row($query);

//Here we have the total row count
$rows = $row[0];

//Number of results to show per page
$page_rows = 5;

//This tells us the page number of our last page
$last = ceil($rows/$page_rows);

//This makes sure last cannot be less than 1
if($last < 1){
    $last = 1;
}
//establish the $pagenum variable
$pagenum = 1;

//Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
    $pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}

//This makes sure the page number isn't below 1 or more than our $last page
if($pagenum < 1){
    $pagenum = 1;
} else if($pagenum > $last) {
    $pagenum = $last;
}
//This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' . ($pagenum - 1) * $page_rows .',' .$page_rows;

//This is your query again, it is for grabbing just one page worth of rows by applying the limit variable
$sql = "SELECT id, caradded, make, color FROM cardetails ORDER BY id DESC $limit";
$query = mysqli_query($dbc, $sql);


//$paginationCrls variable
$paginationCtrls = ' ';

//if there is more than 1 page worth of results
if($last != 1){
    /*First we check if we are on page one.  If we are then we don't need a link to
    the previous page or the first page so we do nothing.  If we aren't then we generate
    links to the first page and to the previous page.*/

    if($pagenum > 1){
        $previous = $pagenum - 1;
        $paginationCtrls .= '<a href="' . $_SERVER['PHP_SELF']. '?pn=' .$previous. '">&#171; Previous</a> &nbsp; &nbsp; ';
        //Render clickable number links that should appear on the left of the target page number
        for($i = $pagenum-4; $i < $pagenum; $i++){
            if($i > 0) {
                $paginationCtrls .= '<a href="' .$_SERVER['PHP_SELF']. '?pn=' . $i .'">'.$i.'</a> &nbsp; &nbsp; ';
            }
        }
    }
//Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' &nbsp; &nbsp; ';
//Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
    $paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a> &nbsp; &nbsp;';
    if($i >= $pagenum+4){
        break;
    }
}
//This adds the same as above only checking if if we are on the last page and then generating Next
if($pagenum != $last){
    $next = $pagenum + 1;
    $paginationCtrls .= ' &nbsp; &nbsp; <a href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'">Next &#187;</a> ';
}
}
//Finish Pagination
?>
<!DOCTYPE html>
<html>
<head>
<title>Basic Page Layout</title>
<link rel="stylesheet" type="text/css" href="basicstyle.css" />
</head>
<body>
    <div id="wrapper">
        <div id="headerwrap">
        <div id="header">
            <p>Search / Filter Practice</p>
        </div>
        </div>
        <div id="leftcolumnwrap">
        <div id="leftcolumn">
                <h2>Trial Filters</h2>
        <form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
        <p>Filter by Date:</p> 
            <input type="radio" name="dateorder" value="dateasc"><label for="dateasc">A - Z</label><br>
            <input type="radio" name="dateorder" value="datedesc"><label for="datedesc">Z - A</label><br>
            <br><hr>
        <p>Filter by Colour:</p>
            <input type="radio" name="color" value="red"><label for="red">Red</label><br>
            <input type="radio" name="color" value="green"><label for="green">Green</label><br>
            <input type="radio" name="color" value="blue"><label for="blue">Blue</label>
            <br><br>
            <input name="submit" type="submit">
            <br><br>
        </div>
        </div>
        <div id="contentwrap">
        <div id="content">
        <p style="text-align:center; font-weight:bold;">My Database Records</p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Car Added On</th>";
echo "<th>Make</th>"; 
echo "<th>Color</th>";
echo "</tr>";
while($row = mysqli_fetch_array($query)){
echo "<tr>";
echo "<td>". $row['caradded'] ."</td>";
echo "<td>". $row['make'] ."</td>";
echo "<td>". $row['color'] ."</td>";
echo "</tr>";
}
print '</table><br><br>';

//close connection to database
mysqli_close($dbc);
?>
<p id="pagination_controls"><?php echo $paginationCtrls;?><br><br>
        </div>
    </div>
        <div id="footerwrap">
        <div id="footer">
            <p>July / August 2016</p>
        </div>
        </div>
    </div>
</body>
</html>

的MySQL

CREATE DATABASE cars;

USE cars;

CREATE TABLE cardetails(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
caradded datetime NOT NULL DEFAULT NOW(),
make VARCHAR(50) NOT NULL,
color VARCHAR(50) NOT NULL);

DESCRIBE cardetails;

INSERT INTO cardetails(caradded, make, color) VALUES
(NOW(), "Toyota", "Red"),
(NOW(), "VW", "Green"),
(NOW(), "Nissan", "Blue"),
(NOW(), "Toyota", "Green"),
(NOW(), "Toyota", "Green"),
(NOW(), "VW", "Blue"),
(NOW(), "VW", "Green"),
(NOW(), "Nissan", "Blue"),
(NOW(), "Nissan", "Green");

SELECT * FROM cardetails; 

1 个答案:

答案 0 :(得分:0)

你的if-Statement中有两个左括号。我在你的源代码中标记了它。
希望能解决你的问题。

编辑2:
当您只为日期顺序选择一个单选按钮时,您始终会获得默认的SQL查询,因为您使用第二个if覆盖日期顺序查询-块。您必须将第二个块放入else if块中。 (见下面的代码)

附加信息:
在此Strucktur中,当您选择共同的颜色和日期过滤器时会出现错误,因为这样您始终只会获得日期查询。要避免此错误,请调用具有相同名称的所有输入字段

<?php
if(isset($_POST['dateorder'])){
        if($_POST['dateorder'] == 'dateasc'){
             //Run query for dateasc
             $query = "SELECT * FROM cardetails ORDER BY caradded asc";
        }elseif($_POST['dateorder'] == 'datedesc'){
             //Run query for datedesc
             $query = "SELECT * FROM cardetails ORDER BY caradded desc";
        }
}else if(isset($_POST['color'])){
        if($_POST['color'] == 'red'){
             //Run query for red color
             $query = "SELECT * FROM cardetails WHERE color = 'red'";
        }elseif($_POST['color'] == 'green'){
             //Run query for green color
             $query = "SELECT * FROM cardetails WHERE color = 'green'";
        }elseif($_POST['color'] == 'blue'){
             //Run query for blue color
             $query = "SELECT * FROM cardetails WHERE color = 'blue'";
        }
}else{
     $query = "SELECT * FROM cardetails ORDER BY id asc";
}
?>

编辑:
由于您在if-Statement之前发送了查询,因此您不会使用更新的查询。之后,您只发送更新的查询,但不要将其保存到$ result。

<强> HTML

<form action="" method="post">
    <p>Date:</p>
    <input id="dateorderasc" type="radio" name="dateorder" onclick="javascript:submit()" value="dateasc"<?php if (isset($_POST['dateorder']) && $_POST['dateorder'] == 'dateasc') echo ' checked="checked"';?> /><label for="dateasc">Newest &rsaquo; Oldest</label>
    <br>
    <input id="dateorderdesc" type="radio" name="dateorder" onclick="javascript:submit()" value="datedesc" <?php if (isset($_POST['dateorder']) && $_POST['dateorder'] == 'datedesc') echo ' checked="checked"';?> /><label for="datedesc">Oldest &rsaquo; Newest</label>
</form>

<强> PHP

<?php
//connect
include ("db.connect.php");

//Retrieve the tasks from the database table
$query = "SELECT * FROM tasks";

//If RadioButton Clicked Sort the Database by Date Asc / Desc
if(isset($_POST['dateorder']) && !empty($_POST['dateorder'])){
    if ($_POST['dateorder'] == 'dateasc'){                  //HERE
        $query .= " ORDER BY date ASC";
    }
    if ($_POST['dateorder'] == 'datedesc'){
        $query .= " ORDER BY date DESC";
    }
}
$result = mysqli_query($dbc, $query) or die('Error Refreshing the page: ' . mysqli_error($dbc));
include("dbresults.php");
?>