2011-03-18 89 views
3

我想做一个函数查询数组,然后我将能够调用单独的值。在这里,我想你会明白我在做什么。除了我是一个完整的初学者。php oop和mysql查询

class Posts{ 

    var $title; 
    var $author; 

    public function querySinglePost($value){ 

    $post = mysql_fetch_array(mysql_query("select * from posts where id=$value")); 
    $this->title = $post['title']; 
    $this->author = $post['author']; 

    } 


} 

如何将数组值分配给类中的变量,然后在我的普通php脚本/视图中调用它们?由于

回答

5

看看mysql_fetch_object。 我也建议使该函数静态,这将返回创建的对象。就像这样:

class Posts{ 

    var $title; 
    var $author; 

    public static function querySinglePost($value){ 

    return mysql_fetch_object(
     mysql_query("select * from posts where id=$value"), 
     __CLASS__); 

    } 

} 

$post = Posts::querySinglePost($value); 
$a = $post->title; 
//... 
+0

如果你正在重构整个事情,不妨抛出一些错误/空结果集处理。 +1“获得”OP后的内容(我认为) – Phil 2011-03-18 14:59:55

+0

我爱你Slava ......你知道吗?这工作完美。谢谢! – Chris 2011-03-18 15:07:25

1

除了没有任何错误处理,不会你只是做类似

$posts = new Posts; 
$posts->querySinglePost(1); 
echo $posts->title; 
echo $posts->author; 
+0

此外,PHP 4死了很久很久以前。 – Phil 2011-03-18 14:57:19

1
$posts = new Posts(); 
$posts->querySinglePost($id); 

echo "return values: \n"; 
echo $posts->title . "\n"; 
echo $posts->author . "\n"; 
0
class Posts{ 

    public $post = array(); 

    public function querySinglePost($value){ 

    // fetch... $results 

    $this->post['title'] = $results['title']; 
    $this->post['author'] = $results['author']; 
    // ... 
    return $this->post; 
    } 
} 

$mySweetPost = new Posts(); 
print_r($mySweetPost->querySinglePost(1)); 
0

你可以在这种情况下,位更有条理。将此类考虑为将扩展基本模型类的模型。而不是直接使用mysql_query,而是使用数据库类并使用它可以执行数据库操作,如查询数据库。插入到数据库等,将其设置为您的基础模型类中的数据库对象。作为一个简单的演示

class model{ 
    public function __construct() 
    { 
    $this->db = new Database(HOST,USER,PASS,DB); 
    } 
} 

class Post extends model{  
public $post; 
public function querySinglePost($value){ 
     $this->post = $this->db->query("select query"); 
     return $this->post; 
    } 
} 

您将调用像

$ObjPost = new Post(); 
$post = $ObjPost->querySinglePost(1);