有人可以帮助我在MySQL LIKE子句中使用具有多个值的变量的正确方法吗?
顺便说一句,我有两个桌子的老师和学生。
教师表包含。 (fname,lname,subject,yr,sec)列和学生表(lrn,yr,sec)
我要达到的目的是计算所有部分中老师的学生总数。
这是我查询教师节的信息:
<?php
$result= mysqli_query($con, "select *from teacher where lname
= 'Uy' and subject = 'Science & Technology 7'" );
while($rowx = mysqli_fetch_array($result)) {
$section = $rowx['sec'];
}
?>
呼应$ section输出以下内容:我们的法蒂玛夫人我们的瓜达卢佩夫人
在这里查询我的学生人数。
<?php
$ratequery = mysqli_query($con, "SELECT *,
(SELECT COUNT(*) FROM student WHERE
sec LIKE '%$section%') AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
?>
输出:计数有效,但是LIKE子句只能识别$ section的第一个值[我们的法蒂玛圣母],因此仅对1个部分进行计数。
顺便说一句,对不起,我的英语不好,也没有解释。
答案 0 :(得分:0)
使用Section作为第二查询的输入:
<?php
$final_result = array();
$result= mysqli_query($con, "select *from teacher where lname
= 'Uy' and subject = 'Science & Technology 7'" );
while($rowx = mysqli_fetch_array($result))
{
$section = $rowx['sec'];
$ratequery = mysqli_query($con, "SELECT *, (SELECT COUNT(*) FROM student WHERE
sec =$section) AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
array_push($final_result,array("section"=>$section,"rateresult"=>$rateresult));
}
var_dump($final_result); // Display section wise data
?>
答案 1 :(得分:0)
我已经设法以其他方式实现了我的目标。我用WHERE IN子句代替LIKE子句。将我的查询结果存储到数组中。然后使用implode添加分隔符。
感谢先生的帮助。 @ashnu
<?php
$query="$con, select *from teacher where lname = 'Uy' and subject = 'Science & Technology 7'";
$result = mysqli_query($query) or die;
$sections = array();
while($row = mysqli_fetch_assoc($result))
{
$sections[] = $row['sec'];
}
$string = implode("','",$sections)
?>
<?php
$ratequery = mysqli_query($con, "SELECT *,
(SELECT COUNT(*) FROM student WHERE sec IN ('$string')) AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
?>