php搜索表由id

时间:2017-03-30 13:36:50

标签: php html mysql

我试图通过id显示数据库表中单行的所有信息。

当我点击搜索时,它显示整个表格,搜索确实没有做任何事情......

任何帮助将不胜感激。谢谢:)

table schema

即时通讯使用php / mysql

<?php 

session_start();
include('connect.php');
if(isset($_POST['search']))
{
$q = $_POST['srch_query'];

?>

<form method="post" action="">
<input type="text" name="srch_query" value="<?php echo $q ?>" required>
<input type="submit" name="search" value="Search">
</form>

<?php

$search = $db->prepare("SELECT species, tree_desc, age, city, state, location FROM tree_info");
$search->execute();
if($search->rowcount()==0){ echo "No product found!"; }
else 
{
    echo "Search Result:</br>";?>
    <table border="1" cellspacing="0" cellpadding="4">
        <thead>
            <tr>
                <th>Species</th>
                <th>Description</th>
                <th>Age</th>
                <th>City</th>
                <th>State</th>
                <th>Location</th>
            </tr>
        </thead>

        <tbody>

    <?php foreach($search as $s)
        { ?>

            <tr class="record">
                <td><?php echo $s['species']; ?></td>
                <td><?php echo $s['tree_desc']; ?></td>
                <td><?php echo $s['age']; ?></td>
                <td><?php echo $s['city']; ?></td>
                <td><?php echo $s['state']; ?></td>
                <td><?php echo $s['location']; ?></td>
            </tr>

    <?php   }
}
} ?>

</tbody>
</table>

2 个答案:

答案 0 :(得分:1)

您应该在查询中使用$q来过滤结果集。目前,您只需将var发送到服务器,而无需对其执行任何操作。

$search = $db->prepare("SELECT species, tree_desc, age, city, state, location FROM tree_info WHERE tree_id=:id");
$search->execute([':id' => (int) $q]);

答案 1 :(得分:-3)

您的$search变量是PDOStatement对象。你需要获取结果。

这样做:

<?php 
    $results = $search->fetchAll();
    foreach($results as $s)
    { ?>

        <tr class="record">
            <td><?php echo $s['species']; ?></td>
            <td><?php echo $s['tree_desc']; ?></td>
            <td><?php echo $s['age']; ?></td>
            <td><?php echo $s['city']; ?></td>
            <td><?php echo $s['state']; ?></td>
            <td><?php echo $s['location']; ?></td>
        </tr>

<?php   }  ?>

如果需要,请查看doc以获取有关PDOStatement的更多信息。 http://php.net/manual/fr/class.pdostatement.php

编辑:我的不好,我专注于错误的问题。

如果查询存在,您必须将$ q添加到您的查询中:

if ($q) {
    $search = $db->prepare("SELECT species, tree_desc, age, city, state,   location FROM tree_info WHERE id = :id");
    $search->bindParam('id', $q, PDO::PARAM_INT);
} else {
    $search = $db->prepare("SELECT species, tree_desc, age, city, state,     location FROM tree_info");
}