我的查询没有找到结果

时间:2014-10-13 13:01:20

标签: php html mysql

我正在尝试此查询,但我无法获得结果。我找不到错误! 这是我的表结构:

id  norm(mediumtext) bohrung(int)       breite(int)     
 2  DIN 5462         26             6           
 3  DIN 5462         28             7           
 4  DIN 5462        32              6           
 5  DIN 5462        36              7           
 6  DIN 5462        42              8           
 7  DIN 5462        46              9       

这是我的SQL查询

<?php       
if (isset($_POST['bohrung'])) {
    $bohrung = $_POST['bohrung'];
    $result = mysqli_query ($con, "SELECT * FROM keilnaben WHERE norm  = {bohrung}");
    if($result && mysqli_num_rows($result) > 0) {
        echo '<table class="table" border="2">
                  <tr>
                     <th>norm</th>
                     <th>norm</th>
                     <th>norm</th>
                  </tr>';
        while($row = mysqli_fetch_array($result)) {
            echo "<tr>
                      <td>" . $row['norm'] . "</td>
                      <td>" . $row['bohrung'] . "</td>
                      <td>" . $row['breite'] . "</td>
                 </tr>";
        }
        echo "</table>";
    }

}

问题在于,当我在文本框中输入例如DIN5462时,查询不会返回任何内容,但如果我对bohrung的{​​{1}}进行同样的尝试,则会返回结果。我不知道为什么。

1 个答案:

答案 0 :(得分:1)

问题在于这一行:

SELECT * FROM keilnaben WHERE norm  = {bohrung}
                                       ^^^
// its a string literal, not a variable

将其更改为此并至少转义输入:

$bohrung = $con->real_escape_string($_POST['bohrung']);
$result = mysqli_query($con,"SELECT * FROM keilnaben WHERE norm  = '$bohrung' ");  

或准备好的陈述:

if (isset($_POST['bohrung'])) {
    $input = $_POST['bohrung'];
    $select = $con->prepare('SELECT * FROM keilnaben WHERE norm = ?');
    $select->bind_param('s', $input);
    $select->execute();
    if($select->num_rows > 0) {
        echo '<table class="table" border="2">
                <tr>
                   <th>norm</th>
                   <th>norm</th>
                   <th>norm</th>
                </tr>';
        $select->bind_result($norm, $bohrung, $breite);
        while ($select->fetch()) {
            echo "<tr>
                      <td>" . $norm . "</td>
                      <td>" . $bohrung . "</td>
                      <td>" . $breite . "</td>
                 </tr>";
        }
        echo "</table>";
    }
}