使用提交按钮显示数据库中的数据

时间:2014-03-17 21:35:22

标签: php mysql

我正在尝试学习php / mysql并使用一个项目,我想要一个提交按钮来显示我从数据库中选择的数据。

我目前正在使用此声明,我希望它是默认的。

$result = mysqli_query($con,"SELECT * FROM persons");

但当有人从我的选择中选择其他内容时,请选择"我希望它改成这样的东西:

$result = mysqli_query($con,"SELECT * FROM persons where firstname='$z'");

所以当有人选择"查理"并按"显示"我只想显示Charlie名字的数据。

您可以在此处关注项目:http://www.adamskymotorkylare.se/business/

先谢谢杰克

<form action="#" method="post">
<select name="first_name" type="text">
<option value="All">All</option>
<option value="Charlie">Charlie</option>
<option value="Bob">Bob</option>
<option value="Sibylla">Sibylla</option>
</select>
<input type="submit" name="submit" value="Show"/>
</form>

<?php
// Create connection

$z = $_POST['first_name'];

$result = mysqli_query($con,"SELECT * FROM persons");

echo "<table width=100%>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Gender</th>
</tr>";

while($row = mysqli_fetch_array($result))
{

$id = $row['id'];

echo "<tr>";
echo "<td> <a href='view_more.php?id=" . $id ."'>" . $row['firstname'] . "</a> </td>";
echo "<td>" . $row['lastname'] .  "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:2)

您只需查看帖子数据:

$query = "SELECT * FROM persons";
if(isset($_POST['first_name'])) {
   $query .= " WHERE firstname='".$_POST['first_name']."'";
}
$result = mysqli_query($con, $query);

请注意,您应该尝试使用预先准备好的语句来保证安全。

答案 1 :(得分:1)

你可以这样做:

if($_POST['first_name']!="All" && isset($_POST['first_name']))
{
    $firstname=htmlentities($_POST['first_name'], ENT_QUOTES);
    $query="SELECT * FROM persons WHERE firstname='".$firstname."'";
}else
{
    $query="SELECT * FROM persons";
}

echo '
                        <select name="first_name">
                            <option value="All">- - - All - - -</option>
';
$dbPersons=mysqli_query($con,"SELECT DISTINCT firstname FROM persons ORDER BY firstname");
while($DataPersons=mysqli_fetch_array($dbPersons))
{
    $selected='';
    if($DataPersons['firstname']==$firstname)
    {
        $selected=' selected="selected"';
    }
    echo '<option value="'.$DataPersons['firstname'].'"'.$selected.'>'.$DataPersons['firstname'].'</option>';
}
echo '              
                        </select>
';

$result = mysqli_query($con,$query);

echo "
    <table width=100%>
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Age</th>
            <th>Gender</th>
        </tr>
";

while($row = mysqli_fetch_array($result))
{
    $id = $row['id'];

    echo "<tr>";
    echo "<td> <a href='view_more.php?id=" . $id ."'>" . $row['firstname'] . "</a> </td>";
    echo "<td>" . $row['lastname'] .  "</td>";
    echo "<td>" . $row['age'] . "</td>";
    echo "<td>" . $row['gender'] . "</td>";
    echo "</tr>";
}
echo "</table>";

mysqli_close($con);

这样您就可以在数据库中选择任何名称。 DISTINCT负责重复。