Php oop and mysql queries

I am trying to create a function that requests an array, and then I can call individual values. Here, I think, you will understand what I'm trying to do. Except that I start with 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 to assign array values ​​to variables in a class and then call them in my regular php script / view? Thanks

+3
source share
5 answers

Take a look at mysql_fetch_object . I would also suggest making this function static, which will simply return the 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;
//...
+5
source

Besides the lack of any kind of error handling, could you just do something like

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

echo "return values: \n";
echo $posts->title . "\n";
echo $posts->author . "\n";
+1
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

In this case, you can be more organized. Consider this class as a model that will expand the base class of the model. Instead of using it directly, mysql_queryuse a database class and using which you can perform database operations, such as querying a database. insert into database etc. set this as a db object in the base class of the model. Like a simple demonstration

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 call as

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

All Articles