Php 使用PDO获取一个MySQL数据库列中有多少个项目实例的列表
我已经在许多论坛和问题上滔滔不绝,这些问题与我试图实现的目标类似(但不尽相同)。我正在将旧的mysql查询更新为PDO。我看到很多人在PDO中使用COUNT(*)时遇到问题,还有一些帖子解释了如何使用query()而不是fetch(),或者使用rowCount()有时使用fetchColumn() 但是,它们似乎用于检查查询是否返回查询中的任何行或零行。可以测试一个查询是否有效,或者返回一行,列出单个查询返回的行数?这不是我想要做的(或者我看错了) 我想要完成的是获得一个列表,其中列出了给定列中每个唯一项出现的次数。我有一个彩弹网站,我想列出多少项目,我为每个类别。旧的mysql代码(为了简洁起见被剪掉)是这样的:Php 使用PDO获取一个MySQL数据库列中有多少个项目实例的列表,php,mysql,count,pdo,Php,Mysql,Count,Pdo,我已经在许多论坛和问题上滔滔不绝,这些问题与我试图实现的目标类似(但不尽相同)。我正在将旧的mysql查询更新为PDO。我看到很多人在PDO中使用COUNT(*)时遇到问题,还有一些帖子解释了如何使用query()而不是fetch(),或者使用rowCount()有时使用fetchColumn() 但是,它们似乎用于检查查询是否返回查询中的任何行或零行。可以测试一个查询是否有效,或者返回一行,列出单个查询返回的行数?这不是我想要做的(或者我看错了) 我想要完成的是获得一个列表,其中列出了给定列中
$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 />";
}
$query=“从表中选择类别,计数(*),其中注释不类似于“已终止”类别分组”;
$result=mysql\u query($query);
$num\u results=$result->num\u行;
而($row=mysql\u fetch\u数组($result,mysql\u NUM)){
回显“$row[0]:$row[1]
”;
}
我的结果是:
空气:312标记:627
口罩:124
油漆:97
等等等等 因此,现在我正试图用PDO获得同样的结果,并尝试了从其他人提出的问题中得出的十几条不同的建议。我通常喜欢自己解决这些问题,这是我第一次不得不认输并在PHP论坛上发布我自己的问题。我把自己弄糊涂了,不知道该往哪条路走了
如果您能从全新的角度提供指导,我们将不胜感激。一定有一种我看不见或误解的方式。提前谢谢 对于任何可能正在为这个概念而挣扎的人,这里是我到目前为止想到的。我相信有更干净的方法可以做到这一点,但目前看来效果不错。由于我还试图将更多面向对象的编码融入到我的技巧包中,因此我最终将解决方案的业务端放入了一个函数中。如果我在重建我的站点时积累了更多,我可能最终会将它们组合到一个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;
}
<?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';
?>
database.ini文件可能看起来很简单,如下所示:
<?php
//database.ini
$db_hostname = 'myHostname';
$db_database = 'databaseNameHere';
$db_username = 'YourUserNameHere';
$db_password = 'YourPasswordHere';
?>
以下是调用函数的方式:
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;
}
<?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项
我希望这能帮助其他人。如果有人能解释一下为什么我的装订不起作用,我将不胜感激。如果没有,我相信我最终会找到答案。您将在PDO中使用相同的查询,并像任何其他查询一样获取结果。。获取“一个项目有多少个实例”没有什么特别的。。这些都是mysql和PDO的结果<代码>$pdo->query('SELECT COUNT()作为myTable中的COUNT')->execute()->fetch(pdo::fetch_OBJ)->COUNT迈克,谢谢你的快速评论。我看到好几页引用不使用fetch(),因为它只返回一行。他们倾向于说要么将其放入while循环,要么使用fetchAll()。有些人说根本不使用它们,而是使用query()。因此,我对所有不同的观点感到困惑。我一直在寻找方向,昨天可能已经找到了如何继续的线索。如果可以的话,我会尝试一下,然后用代码发回,这样其他人可以在需要的时候看到。因为我的查询只会返回一行。您的查询(
SELECT category,count(*)as count…
)将为每个唯一的类别返回两个字段和一行。您应该尝试了解fetch()
、fetchAll()
、query()
等之间的区别,并自行决定如何最好地使用它们。盲目地偏离随机博客的建议,而不理解其背后的原因,将不会教会你任何东西。