PHP-OOP:如何在类外使用PDO fetchAll的结果
我不熟悉PHP和OOP,我一直在使用PDO类从MYSQL数据库连接和检索信息。以下是有关文件的摘要: php.class.phpPHP-OOP:如何在类外使用PDO fetchAll的结果,php,oop,properties,pdo,fetchall,Php,Oop,Properties,Pdo,Fetchall,我不熟悉PHP和OOP,我一直在使用PDO类从MYSQL数据库连接和检索信息。以下是有关文件的摘要: php.class.php <?php class lyrics{ public $con; public $kill; public function __construct(connection $con){ $this->con = $con->con; } public function getLyricsFromURL($lyricsid){
<?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方法中的单个列的结果,我已经尝试过了,但没有成功
正确的方法是什么
提前感谢。方法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>
感谢您的回复,但这不起作用:。收到此错误:致命错误:无法将Lyms类型的对象用作数组不确定这是否有帮助,但我选择将结果作为对象进行回显:$results=$stmt->fetchAllPDO::FETCH_objunderstand,但fetchall应返回基于架构列名的匿名对象数组,应该可以通过标准数组调用访问。你能做一个var_dump$歌词吗;在$lyris=$lyric->getLyricsFromURL55之后;行并将结果发布到?是的,这不是我所期望的,您是否实现了我在回答中概述的代码更改?我不知道你是如何得到一个像你发布的那样的对象构造的。如果调用代码与你在粘贴库中的代码相同,那么问题是你没有使用我建议的更改来更新它。我建议进行建议的更改,看看是否有效。没问题,很高兴听到你的建议。顺便说一句,早早进入PDO的工作做得好,它将帮助你走完这条路。