0

私はPHPとOOPに慣れておらず、PDOクラスを使用してMYSQLデータベースに接続して情報を取得しています。以下は、問題のファイルの抜粋です。

歌詞.class.php

<?php 
class lyrics{

public $con;
public $kill;
public function __construct(connection $con){

    $this->con = $con->con;     
}

public function getLyricsFromURL($lyricsid){
    $results;

    $getlyrics = $this->con->prepare("SELECT * FROM `lyrics` WHERE lyrics_id = :lyricsid");
    $getlyrics->bindParam(':lyricsid',$lyricsid,PDO::PARAM_INT);
    $getlyrics->execute();
    $results = $getlyrics->fetchAll(PDO::FETCH_OBJ);


    foreach ($results as $result) {

        echo $result->lyrics_content;


    }

}

index.php:

<?php
include 'inc/header.php';
include 'libs/connection.class.php';
include 'libs/lyrics.class.php';

$conn = new connection();
$lyrics = new lyrics($conn);

$lyrics->getLyricsFromURL(55);


?>

<h1><?php echo $lyrics->result->lyrics_title;?></h1>

その他: 別のファイルに接続クラスがありますが、ここでは表示しません。接続が機能することを知っているだけです。

問題:*私が抱えている問題は、歌詞クラスの** getLyricsFromURL()メソッドからの結果の個々の列をエコーアウトしたいということです。試しましたが、機能しません。

これを行う正しい方法は何ですか?

前もって感謝します。

4

1 に答える 1

0

このメソッドgetLyricsFromURL()は要素の配列を返すように設定されていますが、戻り値を単一の要素として参照している場合は、次のことを試してください。

public function getLyricsFromURL($lyricsid){

    // This isn't necessary
    //$results;

     // Better to use $stmt as the variable here, obviously this is subjective
     // but will serve you better when you are working on other stmt objects
     $stmt = $this->con->prepare("SELECT * FROM `lyrics` WHERE lyrics_id = :lyricsid");

     $stmt->bindParam(':lyricsid', $lyricsid,PDO::PARAM_INT);
     $stmt->execute();

     $results = $stmt->fetchAll(PDO::FETCH_OBJ);

     return $results;
}

...

// Instatiate our lyrics object
$lyric = new lyrics($conn);

// Make request for lyrics associated to row #55 and store results in local var
$lyrics = $lyric->getLyricsFromURL(55);

// Notice we are referencing the first element of the array
<h1><?php echo $lyrics[0]->lyrics_title;?></h1>
于 2012-07-24T23:38:48.677 に答える