错误:'where子句'中的未知列'abc'

时间:2016-05-26 11:15:37

标签: php mysql mysqli

我有2个下拉菜单。当我点击第一个时,第二个应该显示与第一个选择相关的值。但是当我选择第一个时,我就明白了。

  

错误:'where子句'中的未知列'abc'

下面是我的代码。有人可以告诉我我做错了什么。提前谢谢。

<?php 
include ('db_connect1.php'); 
$query_parent = mysqli_query($conn, "SELECT * FROM field") or die("Query failed: ".mysqli_error());
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {

$("#parent_cat").change(function() {
    $(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
    $.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
        $("#sub_cat").html(data);
        $('#loader').slideUp(200, function() {
            $(this).remove();
        });
    }); 
});

 });
</script>
</head>

<body>
<form method="get">
<label for="category">Parent Category</label>
<select name="parent_cat" id="parent_cat">
    <?php while($row = mysqli_fetch_array($query_parent)): ?>
    <option value="<?php echo $row['field_name']; ?>"><?php echo    $row['field_name']; ?></option>
    <?php endwhile; ?>
</select>
<br/><br/>

<label>Sub Category</label>
<select name="sub_cat" id="sub_cat"></select>
</form>
</body>
</html>

//loadsubcat.php
<?php 
include ('db_connect1.php');

$parent_cat = $_GET['parent_cat'];
$test="SELECT * FROM courses WHERE field_id = {$parent_cat}";
$query = mysqli_query($conn,$test) or die ("Error: ".mysqli_error($conn));
while($row = mysqli_fetch_array($query)) {
echo "<option value='$row[course_id]'>$row[course_name]</option>";
}
?>

2 个答案:

答案 0 :(得分:0)

如果$ parent_cat获得一个值,则需要添加&#34;单引号&#34;,试试这个

$test="SELECT * FROM courses WHERE field_id = '{$parent_cat}'";

你也可以做HAVING而不是WHERE

$test="SELECT * FROM courses HAVING field_id = '{$parent_cat}'";

答案 1 :(得分:0)

字符串值必须在引号内。确保field_idvarcare。更好地使用prepare和bind语句

$parent_cat = $_GET['parent_cat'];
$stmt = $conn->prepare("SELECT * FROM courses WHERE field_id = ?");
    $stmt->bind_param('s', $parent_cat);
    $result = $stmt->execute();

    $stmt->store_result(); //store_result()
    str="";
    if ($stmt->num_rows > 1) { // counts the rows for query.
        while ($row = $result->fetch_assoc()) {
            $str.= "<option value='".$row['course_id']."'>'".$row['course_name']."'</option>";
        }
    }
echo $str;

你的代码是用于sql注入的OPEN。

阅读How can I prevent SQL injection in PHP?以防止它