如何在查询中使用while(foreach)语句中的变量?

时间:2017-03-31 04:05:11

标签: php mysql

我有第一个查询

 <?php 
       while($empsheetpanel=mysqli_fetch_array($resultempsheets)){

 ?>

在此之下我已经放置了第二个查询以便从第一个查询中获取数据

 <?php
 $sql="SELECT * From my_table WHERE id="$empsheetpanel['employee_id']" ";
 $result=mysqli_query($db,$sql);
 ?>
<?php } ;?>

我知道这是不正确和不正确的。从第一个查询中检索$empsheetpanel['employee_id']的正确语法是什么?

3 个答案:

答案 0 :(得分:0)

您需要使用.来连接字符串:

$sql="SELECT * From my_table WHERE id=" . $empsheetpanel['employee_id'];

或者您可以使用字符串插值:

$sql="SELECT * From my_table WHERE id={$empsheetpanel['employee_id']}";

但更好的解决方案不是在循环中将其作为单独的查询来执行。将此表与原始查询一起加入。

因此,如果您的第一个查询是:

SELECT * FROM my_other_table WHERE some conditions here

你会把他们加在一起作为:

SELECT * 
FROM my_other_table
JOIN my_table ON my_table.id = my_other_table.employee_id
WHERE some conditions here

此结果的每一行都包含两个表中数据的组合。如果my_table可能没有匹配的行,则应使用LEFT JOIN代替JOIN

答案 1 :(得分:0)

使用像这样的连接

 }).data('ui-autocomplete')._renderItem = function(ul, item) {
        return $('<div/>')
            .data('ui-autocomplete-item', item)
            .append("<li class='list-group-item'> <div class='row'> <div class='col-md-12'> <div class='media-left media-middle'> <a href='#'> <img class='media-object img-circle' src='http://placehold.it/40x40'> </a> </div> <div id='center'>" + "<a href=/analytics/signals/"+ item.value.split(":")[0].toLowerCase() + ">" +item.value+ "</a>"+ " </div> </div> </div> </li>")
            .appendTo($('#autocompleteTest'));
    };
    $("#x").on("click",function () {
        $("#searchText").val('');

    })
});

答案 2 :(得分:0)

In your first query you can get your result like this:
Your Query:
<?php 
while($empsheetpanel=mysqli_fetch_array($resultempsheets)){
?>

<?php
$sql="SELECT * From my_table WHERE id="$empsheetpanel['employee_id']" ";
$result=mysqli_query($db,$sql);
?>
<?php } ;?>

Response:
<?php 
   $sql = "SELECT * From `my_table`";
   $resultempsheets = mysql_query($sql);
   while($empsheetpanel = mysqli_fetch_array($resultempsheets))
   {
      // put the array index beacuse you are using "mysqli_fetch_array". I am using index "0" here.
      echo $empsheetpanel[0];
      // if you are using "mysqli_fetch_assoc". you can use the filed name to get the value.
      $empsheetpanel['employee_id'];
   }

&GT;

   In your second query you are using the wrong ";" semicolon to terminate the script. you put after the variable define.