0

私は、私が達成しようとしていることと似た (しかし同じではない) 多くのフォーラムや質問にあふれています。古い mysql クエリを PDO に更新しています。PDO での COUNT(*) の使用に問題があるという多くのアカウントと、fetch() の代わりに query() を使用する方法、または rowCount() と場合によっては fetchColumn() を使用する方法を説明するいくつかの投稿を見てきました。

ただし、クエリがクエリで行を返すかゼロかを確認するためのもののようです。クエリが有効かどうかをテストしたり、1 つのクエリで返される行数をリストした 1 行を返したりするにはどうすればよいでしょうか。それは私がやろうとしていることではありません (または私はそれを間違って見ています)。

私が達成したいのは、特定の列で各一意のアイテムが何回出現するかのリストを取得することです。各カテゴリのアイテム数をリストしたいペイントボール Web サイトがあります。古い 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で同じ結果を達成しようとしており、他の人が尋ねた質問から引き出した約12の異なる提案を試しました. 私は通常、これらの問題を自分でハックするのが好きですが、タオルを投げて実際に自分の問題を PHP フォーラムに投稿しなければならなかったのはこれが初めてです。もうどっちが上かわからないほど混乱してしまいました。

新鮮な視点からのガイダンスをいただければ幸いです。私が見ていない、または誤解している方法があるはずです。前もって感謝します!

4

1 に答える 1

1

この概念に苦労しているかもしれない人のために、これが私がこれまでに思いついたものです。これを行うためのよりクリーンな方法があると確信していますが、今のところうまくいくようです。私はまた、より多くのオブジェクト指向コーディングをトリックのバッグに取り入れようとしているので、ソリューションのビジネスエンドを関数に入れることになりました。サイトを再構築するときにさらに2、3を蓄積すると、おそらくそれらを自分用の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
ペイント:
471356アイテム合計

これが誰かの助けになることを願っています。そして、なぜ私のバインディングが機能しなかったのかについて誰かが光を当てることができれば、私はそれを感謝します。そうでなければ、私は最終的にそれを理解すると確信しています。

于 2012-04-15T01:20:01.390 に答える