2013-05-04 47 views
-3

此函數使用PDO計算指定專輯的歌曲。在PDO中計數行

我試着看看什麼是錯,但沒有。 在這裏搜索和bing,什麼都沒有。

function artist_count_songs($id) { 
    global $db; 
    $count = $db->prepare("SELECT COUNT(`song_id`) FROM `songs` WHERE `album_id` = :id"); 
    $count = $count->execute(array(':id' => $id));   
    echo $count; 
} 

有什麼我失蹤了嗎? 試圖rowcolumn仍然沒有

數據庫結構

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; 
SET time_zone = "+00:00"; 

CREATE TABLE IF NOT EXISTS `songs` (
    `song_id` int(11) NOT NULL AUTO_INCREMENT, 
    `album_id` int(11) NOT NULL, 
    `name` varchar(60) COLLATE utf8_unicode_ci NOT NULL, 
    `download_url` varchar(1024) COLLATE utf8_unicode_ci NOT NULL, 
    PRIMARY KEY (`song_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ; 

INSERT INTO `songs` (`song_id`, `album_id`, `name`, `download_url`) VALUES 
(1, 1, 'بحبك اه', 'downloads/tamerhosny/b7bk-ah.mp3'), 
(2, 1, 'بحبك اه', 'downloads/tamerhosny/b7bk-ah.mp3'); 

編輯1

// Count songs total for album 
    function artist_count_songs($album_id) { 
     global $db;   
     $stmt = $db->prepare("SELECT COUNT(`song_id`) FROM `songs` WHERE `album_id` = :album_id"); 
     $success = $stmt->execute(array(':album_id' => $album_id)); 
     list($count) = $stmt->fetch(); 
     echo '<th>'; 
     echo $count; 
     echo '</th>'; 
    } 
+2

參見:http://php.net/manual/en/pdostatement.execute.php 返回TRUE或FALSE的成功失敗。 您需要:http://www.php.net/manual/en/pdostatement.fetch.php – 2013-05-04 20:57:20

+0

請勿重複使用變量名稱。在這裏使用兩個變量而不是一個昂貴的代價。 – hakre 2013-05-04 21:01:00

+0

@hakre謝謝,將牢記在心。 – 2013-05-04 21:11:29

回答

2

$count實際上是一個布爾值,是execute方法的返回值。

$stmt = $db->prepare(
    "SELECT COUNT(`song_id`) FROM `songs` WHERE `album_id` = :id" 
); 
var_dump($stmt); 

$success = $stmt->execute(array(':id' => $id)); 
var_dump($success); 

list($count) = $stmt->fetch(); 
var_dump($count);  
+0

它徹底解決了這個錯誤... 致命錯誤:調用成員函數fetch()在第7行的C:\ wamp \ www \ music \ functions.php中的非對象上獲取() – 2013-05-04 21:04:04

+0

@SaebMsarwa你可以顯示你的代碼? – 2013-05-04 21:05:29

+0

看看>> https://github.com/SaebMsarwa/music – 2013-05-04 21:10:08