标题和标题的标签用函数获取

时间:2012-10-12 23:33:40

标签: php mysql


我想获取标题和标题的标签。

public function titles()
{
     $query=mysql_query("SELECT * FROM title");
     while($row = mysql_fetch_object($query)){
          $data->title[] = $row;
          $data->tag[] = $this->tags($row->id);
     }
     return $data;
}

public function tags($title_id)
{
     $query=mysql_query("SELECT * FROM tag WHERE title_id = '$title_id'");
     while($row = mysql_fetch_object($query)){
           $tag[] = $row;
     }
     return $tag;
}

我正试图以这种方式打印

$data = titles();
foreach($data->title as $title)
{
     echo $title->topic;
     foreach($data->tag as $tag)
     {
         echo $tag->name;
     }
}

但它不起作用。我能怎么做? 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

你的标题方法应该有这样的东西

$data = new stdClass();
$data->title = array();
$data->tag = array();

您还需要添加此类文件

$data->title[$row->id][] = $row;
$data->tag[$row->id][] = $this->tags($row->id);

然后你可以像这样循环

foreach($data->title as $id => $title)
{
    echo $title->topic;
    foreach($data->tag[$id] as $tag)
    {
        echo $tag->name;
    }
}

同时启用错误,以便您可以在页面顶部看到PHP错误..

error_reporting(E_ALL);
ini_set("display_errors","On");

PHP DOC ON mysql_***

  

不鼓励使用此扩展程序。相反,应该使用MySQLi或PDO_MySQL扩展。另请参阅MySQL:选择API指南和相关的常见问题解答以获取更多信息。该功能的替代方案包括

我认为您的代码应该是什么样的

class Somthing {
    private $db;

    function __construct() {
        $this->db = new mysqli("localhost", "user", "password", "db");
    }

    function titles() {
        $data = new stdClass();
        $data->title = array();
        $data->tag = array();

        $result = $this->db->query("SELECT * FROM title");
        while ( $row = $result->fetch_object() ) {
            $data->title[$row->id] = $row;
            $data->tag[$row->id] = $this->tags($row->id);
        }
        return $data;
    }

    function tags($title_id) {
        $tag = array();
        $result = $this->db->query("SELECT * FROM tag WHERE title_id = '$title_id'");
        while ( $row = $result->fetch_object() ) {
            $tag[] = $row;
        }
        return $tag;
    }
}

$somthing = new Somthing();

foreach ($somthing->titles() as $id => $title ) {
    echo $title->topic;
    foreach ( $data->tag[$id] as $tag ) {
        echo $tag->name;
    }
}
相关问题