使用PDO获取MySQL数据库列中项目实例的列表

时间:2012-04-08 01:36:38

标签: php mysql count pdo

我一直在倾注许多论坛和类似(但不一样)的问题,正如我想要完成的那样。我正在将我的旧mysql查询更新为PDO。我看过许多人在PDO中使用COUNT(*)时遇到问题,有几篇文章解释使用query()而不是fetch(),或者使用rowCount(),有时使用fetchColumn()。

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

我想要完成的是获取每个唯一项目在给定列中出现的次数的列表。我有一个彩弹网站,我想列出每个类别有多少项目。旧的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论坛上发布自己的问题。我已经让自己变得如此困惑,我不知道哪个方向了。

从新的角度来看,任何指导都会非常感激。必须有一种我没有看到或误解的方式。谢谢!

1 个答案:

答案 0 :(得分: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项

我希望这可以帮助那些人。如果有人能说明为什么我的装订不起作用,我会很感激。如果没有,我相信我最终会弄明白。