开发者

php oop and mysql query

开发者 https://www.devze.com 2023-02-18 04:35 出处:网络
I am trying to make a function that queries an array, and then I will be able to call the separate values. Here, I think you will understand what I am trying to do. Except I am a complete beginner to

I am trying to make a function that queries an array, and then I will be able to call the separate values. Here, I think you will understand what I am trying to do. Except I am a complete beginner to this.

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 = $p开发者_如何学Cost['author'];

  } 


}

How can I assign the array values to variables in the class, and then call them in my normal php script/view? Thanks


Take a look at mysql_fetch_object. I'd also suggest to make that function static which will just return created object. Like this:

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;
//...


Apart from the lack of any error handling, wouldn't you just do something like

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


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

echo "return values: \n";
echo $posts->title . "\n";
echo $posts->author . "\n";


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));


You can be bit more organized in this case. Consider this class as a model which will extend a base model class. Instead of directly using mysql_query, use a database class and using which u can DO database operations like querying the database. insert into database, etc. set this as the db object in your base model class. As a simple demo

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;
    }
}

You will be calling like

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

精彩评论

暂无评论...
验证码 换一张
取 消