所以我有两个表用户(IDN,RoP)和search_info(IDN,位置,年龄)(IDN - 是一个关键列) 我需要收集并计算数据库中具有正确类型(RoP)和正确信息(位置和年龄)的行。
所以php:
$location = $_POST['location'];
$age = $_POST['age'];
$type=$_SESSION['type'];
然后我制作了mysql代码......它不是选择原始数据,而是计算它们。我知道查询不再使用,但我将其用于教育目的。
$search_result= mysql_query("
SELECT COUNT(a.IDN)
FROM users AS a LEFT JOIN info_search AS b
ON a.IDN = b.IDN
Where a.RoP='$s_type' AND b.Location = '$location' AND b.Age = '$age'
");
$search=mysql_fetch_array($search_result);
因此,您可以看到代码正在运行,但在这里工作人员。我发送了位置1,2或3,否则为0.所以如果location == 0我想从数据库行中获取而不管位置(换句话说 - 任何位置)。与年龄相似。是否有可能在MYSQL上实现?如何更改MYSQL抓取任何位置的变量? 和代码中的最后一个问题。我正在尝试选择需求数据,但输出它们有问题。那么怎么打印出来呢?
$search_result= mysql_query("
SELECT COUNT(a.IDN), a.IDN, b.location, b.age
FROM users AS a LEFT JOIN info_search AS b
ON a.IDN = b.IDN
Where a.RoP='$s_type' AND b.Location = '$location' AND b.Age = '$age'
");
i=0;
while ($search=mysql_fetch_array($search_result))
{
$ar_result[] = $search; // some how I get only first row not all of them
$i++;
}
答案 0 :(得分:1)
首先:
<?php
$location = (int) $_POST['location'];
$age = (int) $_POST['age'];
$type=$_SESSION['type'];
$and_where = array();
if( $age )
{
$and_where [] = "b.Age = '{$age}'";
}
if( $location )
{
$and_where [] = "b.Location = '{$location}'";
}
if( ! empty( $and_where ))
{
$and_where = ' AND ' . implode( ' AND ', $and_where);
} else {
$and_where = '';
}
$sql = "SELECT COUNT(a.IDN) ".
"FROM users AS a LEFT JOIN info_search AS b ".
"ON a.IDN = b.IDN Where a.RoP='{$s_type}'" . $and_where;
?>
第二
$search_result= mysql_query("
SELECT COUNT(a.IDN) as cnt, a.IDN, b.location, b.age
FROM users AS a LEFT JOIN info_search AS b
ON a.IDN = b.IDN
Where a.RoP='$s_type' AND b.Location = '$location' AND b.Age = '$age'
");
i=0;
while ($search=mysql_fetch_array($search_result))
{
$ar_result[] = $search ['cnt']; // some how I get only first row not all of them
$i++;
}