2012-04-08 1 views
0

나는 많은 포럼과 질문을 수행하려고하는 것과 비슷하지만 비슷하지는 않습니다. 나는 이전의 mysql 쿼리를 PDO로 업데이트 중이다. 사람들이 PDO에서 COUNT (*)를 사용하는 데 어려움을 겪고 있고 여러 게시물에서 fetch() 대신 query()를 사용하거나 rowCount() 및 fetchColumn()을 사용하여 설명하는 여러 게시물을 보았습니다.PDO를 사용하여 MySQL 데이터베이스 열에있는 항목의 인스턴스 수를 얻으십시오.

그러나 쿼리에서 쿼리가 0 또는 0 행을 반환하는지 확인하는 것으로 보입니다. 쿼리가 유효한지 테스트하거나 단일 쿼리에서 반환하는 행의 수를 나열하는 단일 행을 반환 할 수 있습니까? 그게 내가하려는 일이 아니야. (아니면 내가 잘못보고있다.)

내가 원하는 것은 각 고유 항목이 주어진 열에서 몇 번이나 나왔는지에 대한 목록을 얻는 것입니다. 나는 내가 각 카테고리에 대해 얼마나 많은 아이템을 갖고 싶은지 페인트 볼 웹 사이트를 가지고있다. (간결 냈다) 이전 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 포럼에 내 문제를 게시해야하는 첫 번째 사건이다. 나는 너무 혼란스러워서 더 이상 어떤 길을 찾지 못했습니다.

신선한 관점에서의 안내는 대단히 감사하겠습니다. 내가 보거나 오해하지 않는 방법이 있어야합니다. 미리 감사드립니다!

+0

당신은 PDO에서 같은 쿼리를 사용하고 다른 쿼리와 마찬가지로 결과를 가져옵니다. '아이템의 인스턴스 수'를 가져 오는 것은 특별한 것이 아닙니다. mysql과 PDO의 모든 결과입니다. '$ pdo-> query ('SELECT COUNT() from count from myTable') -> execute() -> 가져 오기 (PDO :: FETCH_OBJ) -> 카운트, ' –

+0

빠른 코멘트를 주셔서 감사합니다. 필자는 fetch()를 사용하지 않기로 한 여러 페이지를 보았습니다. 왜냐하면 단일 행만 반환하기 때문입니다. while 루프에 넣거나 fetchAll()을 사용하는 경향이 있습니다. 어떤 사람들은 그것들을 전혀 사용하지 않는다고 대신 query()를 사용합니다. 그러므로 다른 견해들 모두에서의 혼란의 일부. 나는 방향을 찾기를 계속했고 어제 어떻게 진행해야하는지에 대한 힌트를 발견했을 것입니다. 다른 사람들이 필요할 때 코드를 볼 수 있도록 코드가 있으면 코드를 다시 게시 해 보겠습니다. – Tam

+0

내 쿼리는 한 행만 반환하기 때문에. 귀하의 질의 ('SELECT category, count (*) as count ...)는 모든 고유 한 카테고리에 대해 두 개의 필드와 행을 반환합니다. –

답변

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 항목

나는이 밖에 다른 사람 도움이되기를 바랍니다

총.그리고 왜 누군가가 나의 구속력이 작동하지 않는지에 관해 밝힐 수 있다면, 나는 그것을 고맙게 생각할 것입니다. 그렇지 않다면 나는 결국 그것을 알아낼 것이라고 확신한다.

관련 문제