简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM