2012-04-08 82 views
0

我一直在倾注很多论坛和类似(但不是相同的)我想要完成的问题。我正在更新我的旧mysql查询到PDO。我看到很多人在使用COUNT(*)在PDO中遇到困难,并且有几篇文章用query()而不是fetch()或者使用rowCount()和fetchColumn()来解释。使用PDO获取项目在一个MySQL数据库列中有多少实例的列表

但是它们似乎用于检查查询是否返回查询中的任何或零行。也许可以测试一个查询是否有效,或返回单行列出单个查询返回多少行?这不是我想要做的(或者我看错了)。

我想完成的是获得每个唯一项目在给定列中出现次数的列表。我有一个彩弹网站,我想列出每个类别有多少项目。旧的MySQL代码(剪断为了简洁)是这样的:

$query = "SELECT Category, COUNT(*) FROM table WHERE Notes NOT LIKE 'Discontinued' GROUP BY Category"; 
    $result = mysql_query($query); 
    $num_results = $result->num_rows; 

    while($row=mysql_fetch_array($result, MYSQL_NUM)) { 
    echo "$row[0]: $row[1]<br />"; 
    } 

我的结果将是:

航空:312
标记:627个
面具:124
油漆:97
等等等等

所以,现在我试图完成与PDO相同的结果,并尝试了大约我从其他问题拉出了十几个不同的建议 问过了。我通常喜欢自己破解这些问题,这是我第一次不得不扔在毛巾上,实际上在PHP论坛上发布自己的问题。我已经弄得自己很困惑,我不知道哪条路了。

任何从全新角度的指导将非常感激。必须有一种我没有看到或误解的方式。提前致谢!

+0

你会在PDO中使用相同的查询,并像其他任何查询一样获取结果。没有什么特别的提取'项目的多少个实例'..这些都是mysql和PDO的结果。 '$ pdo-> query('SELECT COUNT()as count FROM myTable') - > execute() - > fetch(PDO :: FETCH_OBJ) - > count;' – 2012-04-08 02:03:55

+0

感谢您的快速评论,Mike。我见过几个不引用fetch()的页面,因为它只返回一行。他们倾向于说要么把它放在while循环中,要么使用fetchAll()。有人说根本不使用它们,而是使用query()。因此,我对所有不同的观点有些混淆。我一直在继续寻找方向,昨天可能会提示如何继续。我会试一试,如果它能正常工作,可以回传代码,以便其他人在需要时可以看到它。 – Tam 2012-04-11 18:20:53

+0

因为我的查询只会返回一行。你的查询('SELECT category,count(*)as count ...')会为每个唯一类别返回两个字段和一行。 – 2012-04-11 18:28:00

回答

1

对于任何人可能正在为这个概念而努力,这是我到目前为止所提出的。我确信有这样做的更干净的方法,但它现在似乎工作正常。由于我也试图将更多面向对象的编码融入到我的一揽子技巧中,因此我最终将解决方案的业务端放入功能中。如果我在重建我的网站时积累了更多的内容,我可能会最终将它们组合到一起,形成一个PDO包装类,或者其他类似的东西。

这里是我的功能:

function fieldCount($field,$condition,$table) 
{ 
//This is just a file that holds the database info and can be whatever name you want 
require('database.ini'); 
try{ 
    $dbh = new PDO("mysql:host=$db_hostname;dbname=$db_database", $db_username, $db_password); 

    //This turns on the error mode so you get warnings returned, if any 
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    $stmt = $dbh->prepare("SELECT $field, COUNT(*) AS count FROM $table $condition GROUP BY $field"); 

// I tried to bind my $field variable but for some reason it didn't work so I 
// commented it out below until I can look deeper into it. If anyone sees any 
// glaring errors, please point them out. It looks right to me, but as I said, 
// it's not working. 

// $stmt = $dbh->prepare("SELECT :field, COUNT(*) AS count FROM $table $condition GROUP BY :field"); 
// $stmt->bindParam(':field', $field); 

    $stmt->execute(); 

    $results=$stmt->fetchAll(PDO::FETCH_ASSOC); 
    // Creates an array similar as the following: 
    // $results[0][$field] $results[0]['count'] 
    // $results[1][$field] $results[1]['count'] 
    // $results[2][$field] $results[2]['count'] 
    // with each row as an array of values within a numeric array of all rows 

    $dbh = null; 
} 
catch(PDOException $e) 
{ 
echo $e->getMessage(); 
} 

return $results; 
} 

的database.ini文件看起来如此简单的东西:

<?php 
    //database.ini 

    $db_hostname = 'myHostname'; 
    $db_database = 'databaseNameHere'; 
    $db_username = 'YourUserNameHere'; 
    $db_password = 'YourPasswordHere'; 
?> 

这里是你如何调用该函数:

<?php 
// First you have to "require" your file where the function is located, 
// whatever you name it. 
require('FieldCountFunction.php'); 

// Determine what column in your database you want to get a count of. 
// In my case I want to count how many items there are in each individual 
// category, so the $field is Category here. 
$field = 'Category'; 

// If there is a condition to your query, you would state it here. 
// In my case I wanted to exclude any items in my Inventory table that 
// are marked "Discontinued" in the Notes column of my database. 
$condition = "WHERE Notes NOT LIKE 'Discontinued'"; 

$DB_Table = 'Inventory'; 

// Now you call the function and enter the $field you want to get a count of, 
// any conditions to the query, and the database table name you are querying. 
// The results you collected in the function (it was called $results above), 
// will be dumped into a new array now called "$fieldArray" below. 
$fieldArray = fieldCount($field, $condition, $DB_Table); 

// To get the data out again you can do the following to cycle through the 
// numeric array of rows (that's what the "$i" is for) and from each numbered 
// row you can retrieve the "$field" and "count" that you need. Then display 
// them however you want. I'll just echo them out here. 
$i=0; 
while($i<count($fieldArray)) 
{ 
    echo $fieldArray[$i]["$field"].' : '.$fieldArray[$i]['count'].'<br />'; 
    $totalCount = $totalCount + $fieldArray[$i]['count']; 
    $i++; 
} 
echo $totalCount.' items total'; 
?> 

这将给出类似于以下的结果:

配件:638个
标记:432个
面具:146个
包:93
油漆:47个
1356项目总

我希望这可以帮助一个人在那里。如果任何人都可以阐明为什么我的绑定不起作用,我会很感激。如果没有,我相信我会最终弄清楚。

相关问题