0

So i'm new to classes and functions and I'm trying to do one sql query for the entire class for every function to use. I'm a little confused on how it works. From other examples that I've seen the call the query every single function which seems like a lot of usage. (why not call it once and set them all) I know there is an easier way by just querying and making variables including a db file or whatever. This is just practice.

<?php
//User System
class usrsys
{

 $results = mysqli_query($con, "SELECT * FROM users WHERE id = '".$_SESSION['coid']."'");

while($row = mysqli_fetch_array($results))      { 

    $fname = $row['fname'];
                                    }

    function username()
    {
            echo $_SESSION['Username'];

    }

    function fname()
    {
            echo $fname;

    }                           
}


//Setting Variable
$user = new usrsys();
?>

Then I call the functions in the next file by:

<?php $user->fname(); ?>

1 Answers1

0
class usrsys
{
public $fname;
public $con;
public function __construct() {
     //load your conection class function here and pass it to the $this->con variable.
     $results = mysqli_query($this->con, "SELECT * FROM users WHERE id = '".$_SESSION['coid']."'");
        while($row = mysqli_fetch_array($results)) { 
            $this->fname = $row['fname'];
        }
}
    function username()
    {
            echo $_SESSION['Username'];

    }

    function fname()
    {
            echo $this->fname;

    }                           
}


//Setting Variable
$user = new usrsys();
$user->fname();
Sachin Tyagi
  • 133
  • 6
  • I didn't understand the `$this` variable until i read [link](http://stackoverflow.com/questions/1523479/what-does-the-variable-this-mean-in-php) Your example was what I was looking for! Thank you! –  Aug 29 '15 at 17:46