0

我一直在倾诉许多与我想要完成的类似(但不一样)的论坛和问题。我正在将旧的 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 论坛上实际发布我自己的问题。我已经把自己弄得很糊涂了,我不知道该往哪边走。

任何从新角度的指导将不胜感激。一定有一种我没有看到或误解的方法。提前致谢!

4

1 回答 1

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 件

我希望这可以帮助那里的人。如果有人能解释为什么我的绑定不起作用,我将不胜感激。如果没有,我相信我最终会弄清楚的。

于 2012-04-15T01:20:01.390 回答