Chris
Chris

Reputation: 461

php oop and mysql query

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 = $post['author'];

  } 


}

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

Upvotes: 3

Views: 2147

Answers (5)

Shameer
Shameer

Reputation: 3066

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

Upvotes: 0

Slava
Slava

Reputation: 2050

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

Upvotes: 5

miqbal
miqbal

Reputation: 2227

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

Upvotes: 0

Artur Marnik
Artur Marnik

Reputation: 116

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

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

Upvotes: 1

Phil
Phil

Reputation: 164776

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;

Upvotes: 1

Related Questions