你如何在另一个文件的SQL查询中使用php变量?

时间:2017-12-11 08:52:40

标签: php mysqli

我试图仅显示我的数据库中由网站访问者确定的特定品牌的结果。我的index.php需要获取值才能在SQL查询中使用它。需要更新此查询,以使结果与所选品牌相关。我想要用于品牌的变量是$branddata

index.php(结果在哪里)

<div class="list-group">
    <h3>Model</h3>
    <?php               
        $query = "select distinct(Model) from Sheet1 order by Brand ASC";  
        $rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));
        while($model_data = mysqli_fetch_assoc($rs)){ 
    ?>
        <a href="javascript:void(0);" class="list-group-item"> 
         <input type="checkbox" class="item_filter model" value="<?php echo $model_data['Model']; ?>" >&nbsp;&nbsp; <?php echo $model_data['Model'];?>
        </a>
    <?php } ?>  
</div>

ajax.php(我想从中检索变量)

<?php
include"conf.php"; 
$brand="";
$brand = isset($_REQUEST['brand'])?$_REQUEST['brand']:"";

$query = "select * from Sheet1 where"; 

//filter query start 
if(!empty($brand)){
    $branddata =implode("','",$brand);
    $query  .= " Brand in('$branddata') and";
}
?>

结果应该是index.php中的SQL查询,它在更新变量$branddata时进行更新。示例查询:Select distinct(Model) from Sheet1 where Brand in('$branddata') order by Brand ASC

1 个答案:

答案 0 :(得分:0)

使用heredoc syntax

<?php
include"conf.php"; 
$brand="";
$brand = isset($_REQUEST['brand'])?$_REQUEST['brand']:"";



        $query = "select * from Sheet1 where"; 

                   //filter query start 
                      if(!empty($brand)){
                          $branddata =implode("','",$brand);
                          $query  .= <<<CHAINE Brand in('$branddata') and

CHAINE; 
    }