2009-04-20 91 views
0

我有一个表与各种拍卖,其中每个记录都有用户名和类别。很可能,会有多个具有相同用户名和类别的记录。有四种不同的类别。动态命名变量?

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

$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应返回

对于用户名和蒂莫类假,1应返回

对于用户名和wenx类别确定; 2应返回。

我希望能够打印出像这样:在一个循环中

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']"; 
    } 
} 

回答

0

试试这个

Fake items: $numfake items or category['fake'] 
OK items: $numok items or category['ok'] 
Sold items: $numsold items or category['sold'] 
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; 
+0

我需要能够打印出像 假项目:$ numfakeitems 销售的物品:$ numsolditems oktiems:$ numokitems等,这就是为什么我认为它是有道理的使用数组。目前我不认为我可以只用一个变量来做到这一点,除非我误解了。 – 2009-04-20 14:20:06