动态命名变量?

时间:2009-04-20 14:05:47

标签: php sql mysql

我有一张包含各种拍卖的表格,其中每张唱片都有用户名和类别。更有可能的是,将有多个具有相同用户名和类别的记录。有四种不同类型的类别。

我想知道在下面准备好的查询中是否有可能让第二个绑定参数成为循环包含4个类别的数组的结果,并且我是否可以动态地将结果分配给数组? / p>

$countAuctionsQuery = "select COUNT(USERNAME, SUBCAT) from AUCTIONS where username = ? AND SUBCAT = ?";

    if ($getRecords = $con->prepare($countAuctionsQuery)) 
        {
        $getRecords->bind_param("ss", $username, $subcat);
        $getRecords->execute();        
        $getRecords->bind_result($numRecords);
         }

编辑:

数据示例

Auctions


username    itemnumber  cost    category
------------------------------------------------
fredx       222     $33 fake
fredx       123     $43 fake
timo        765     $54 fake
fredx       987     $99 sold
bobk        233     $77 fake
wenx        11      $12 ok
fredx       23      $31 ok
fredx       723     $73 fake
wenx        44      $88 ok

因此,对于用户名fredx和类别假,应该返回3。

对于用户名fredx和已售出的类别,应返回1

对于用户名timo和类别假,应返回1

对于用户名wenx和类别ok,应返回2.

我希望能够像这样打印出来:

Fake items: $numfake items or category['fake']
OK items: $numok items or category['ok']
Sold items: $numsold items or category['sold']

2 个答案:

答案 0 :(得分:0)

使用此:

SELECT  subcat, COUNT(*)
FROM    AUCTIONS
WHERE   username = ?
GROUP BY
        subcat

并在循环中获取结果:

$countAuctionsQuery = $query;

if ($getRecords = $con->prepare($countAuctionsQuery)) {
    $getRecords->bind_param("s", $username);
    $getRecords->execute();        
    $getRecords->bind_result($subcat, $numRecords);
    while ($getRecords->fetch()) {
        print "$subcat items: $numRecords items of category['$subcat']";
    }
}

答案 1 :(得分:0)

试试这个:

function getCategoryCount($user, $conn) {
    $result = array();
    $query = "SELECT category, COUNT(id) AS count FROM Auctions
              WHERE username=? GROUP BY category";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('s',$user);
    $stmt->execute();
    $stmt->bind_result($cat, $count);
    while ($stmt->fetch()) {
        $result[$cat] = $count;
    }
    return $result;
}

您可以使用以下功能:

$count = getCategoryCount('fred', $con);
print $count['fake']; // prints '3'

相反,你也可以这样做:

$query = "SELECT category, COUNT(id) AS count FROM Auctions
          WHERE username=? GROUP BY category";
$stmt = $con->prepare($query);
$stmt->bind_param('s',$user);
$user = 'fred';
$stmt->execute();
$stmt->bind_result($cat, $count);
while ($stmt->fetch()) {
    ${'num'.$cat} = $count;
}

print $numfake;
print $numok;
print $numsold;