Jump to content

OOP - Passing Data/Variables Between Functions


Joe90k
Go to solution Solved by Joe90k,

Recommended Posts

Hi All,

 

I am looking for some advice, I am trying to create something using OO php but struggling really.

/* MySQL Columns & Types
Id - Primary Key (Index), Auto Increment - Int (11)
Title - Varchar (20) 
FirstName - Varchar (60)
LastName - Varchar (60)
*/

class client
{
	
	//Connect to MySQL	
	public function __construct()	
	{
		$mysqli = new mysqli("localhost", "test", "test", "test");
		
		if($mysqli->error)
			die($mysqli->error);
	}
	
	//These functions build the insert query so they can be called one at a time or all at once
	public function setTitle($title)
	{
		$this->title = $title;	
	}
	
	public function getTitle()
	{
		echo $this->title;
	}
	
	public function setFirstName($firstname)
	{
		$this->firstname = $firstname;	
	}
	
	public function getFirstName($te)
	{
		echo $this->firstname;
	}
	
	public function setLastName($lastname)
	{
		$this->lastname = $lastname;
	}
	
	public function getLastName()
	{
		echo $this->lastname;
		
	}
	
public function load($client_id)	
	{
		
		$data = array();
		$mysqli = new mysqli("localhost", "test", "test", "test");
		//function to retrieve client info from db
		$query = "SELECT * FROM mysql WHERE id = " . $client_id;
		$sql = $mysqli->query($query);
		if($sql->num_rows > 0) {
			while ($row = $sql->fetch_assoc()) {
				$te = $row['title'];
				$fn = $row['firstname'];
				$ln = $row['lastname'];
			}
			return $row;
		} else {
		echo "Client Not Found!";	
		} 
	}
	
	public function save()
	{
		
		if ($check->Rows() > 0)	{
		//update
		$mysqli->query("UPDATE clients SET $cloumns");
		} else {
		//insert
		$query = "INSERT INTO mysql (".$columns.")VALUES (.".$values.".)";
		$mysqli->query($query);
		}
		$sql->close();
		
    } 
}

I am trying to using the load method with an id number to get the data from MySQL which works fine, however I then want to be able to edit this using various functions to build an update query. I also want to be able to insert a new query. I think I can do this all under the save() method, but I am not sure. I am not new to php but very new to OOP so am struggling to see how it all links together.

 

Any help would be grand!

 

:happy-04:

 

(P.S. My code is all over the place as I have been experimenting, please chop and change it if you need to.)

Edited by Joe90k
Link to comment
Share on other sites

It's really not clear what your goals are here sorry. How/Why exactly are you planning on using the results from a SELECT statement to build an UPDATE statement?

 

A bit OT too but why the while() loop?

 

ps: Just because your using classes, doesn't make your code OOP either. There is a hell of a lot more to it than that.

Link to comment
Share on other sites


<?php
/* MySQL Columns & Types
Id - Primary Key (Index), Auto Increment - Int (11)
Title - Varchar (20)
FirstName - Varchar (60)
LastName - Varchar (60)
*/

class client
{
private $_mysqli;
private $_title;
private $_firstName;
private $_lastName;


//Connect to MySQL
public function __construct()
{
$this->_mysqli = new mysqli("localhost", "test", "test", "test");

if ($this->_mysqli->error) {
throw new Exception($this->_mysqli->error);
}

}

//These functions build the insert query so they can be called one at a time or all at once
public function setTitle($title)
{
$this->_title = $title;
}

public function getTitle()
{
echo $this->_title;
}

public function setFirstName($firstname)
{
$this->_firstName = $firstname;
}

public function getFirstName($te)
{
echo $this->_firstName;
}

public function setLastName($lastname)
{
$this->_lastName = $lastname;
}

public function getLastName()
{
echo $this->_lastName;

}

public function load($client_id)
{

$data = array();
//the follwoing is on the principle of a single result
$query = "SELECT * FROM mysql WHERE id = " . $client_id;
$sql = $this->_mysqli ->query($query);
if($sql->num_rows > 0) {
while ($row = $sql->fetch_assoc()) {
$this->_title = $row['title'];
$this->_firstName = $row['firstname'];
$this->_lastName = $row['lastname'];

// now you have done this you will have a populated object. so the get the firstname you do $client->getFirstname()
}
} else {
throw new Exception('client not found');
}
}

// you should be able to figure the rest out
/*public function save()
{

if ($check->Rows() > 0) {
//update
$mysqli->query("UPDATE clients SET $cloumns");
} else {
//insert
$query = "INSERT INTO mysql (".$columns.")VALUES (.".$values.".)";
$mysqli->query($query);
}
$sql->close();

}*/
}
Link to comment
Share on other sites

I've found out two things about OOP, one that first one should be able to write  Procedural code fairly easily. Second sometimes is best to stick doing it the procedural way, specially if it's a small project. A good book I recommend is "PHP Advanced and Object-Oriented Programming" by Larry Ullman (3rd Ediition...although a 4th Edition might have come out). It's the first book that I have gone through the first chapter (I'm currently reading Chapter 11), that I haven't skipped anything and have followed the tutorials faithfully. It's interesting what you can do with just plain PHP (procedural code). Even after reading the book I still have a lot to learn for there are design patterns that you have to decide what direction you want to take OOP and that is best to do that from the start of the project. 

Link to comment
Share on other sites


<?php
/* MySQL Columns & Types
Id - Primary Key (Index), Auto Increment - Int (11)
Title - Varchar (20)
FirstName - Varchar (60)
LastName - Varchar (60)
*/

class client
{
    private $_mysqli;
    private $_title;
    private $_firstName;
    private $_lastName;


    //Connect to MySQL
    public function __construct()
    {
        $this->_mysqli = new mysqli("localhost", "test", "test", "test");

        if ($this->_mysqli->error) {
            throw new Exception($this->_mysqli->error);
        }
        
    }

    //These functions build the insert query so they can be called one at a time or all at once
    public function setTitle($title)
    {
        $this->_title = $title;
    }

    public function getTitle()
    {
        echo $this->_title;
    }

    public function setFirstName($firstname)
    {
        $this->_firstName = $firstname;
    }

    public function getFirstName($te)
    {
        echo $this->_firstName;
    }

    public function setLastName($lastname)
    {
        $this->_lastName = $lastname;
    }

    public function getLastName()
    {
    echo $this->_lastName;

    }

    public function load($client_id)
    {

    $data = array();
    //the follwoing is on the principle of a single result
    $query = "SELECT * FROM mysql WHERE id = " . $client_id;
    $sql = $this->_mysqli ->query($query);
    if($sql->num_rows > 0) {
        while ($row = $sql->fetch_assoc()) {
        $this->_title = $row['title'];
        $this->_firstName = $row['firstname'];
        $this->_lastName = $row['lastname'];
            
            // now you have done this you will have a populated object. so the get the firstname you do $client->getFirstname()
        }
    } else {
        throw new Exception('client not found');
    }
    }
    
    // you should be able to figure the rest out
    /*public function save()
    {

    if ($check->Rows() > 0)	{
    //update
    $mysqli->query("UPDATE clients SET $cloumns");
    } else {
    //insert
    $query = "INSERT INTO mysql (".$columns.")VALUES (.".$values.".)";
    $mysqli->query($query);
    }
    $sql->close();

    }*/
}

Thanks, that was exactly what I was after, it seems the simple things are making me fall over at the moment, I think I am overcomplicating something that is simpler than it seems at first look.

 

I run the following and it returns nothing:

$client_id;

// retrieve client record 
$c = new client();
if ($c->load($client_id)) {
    echo $c->getTitle() . " " . $c->getFirstname() . " " . $c->getLastName();
}  

However if I run:

$c = new client();
$c->load(3);
echo $c->getTitle() . " " . $c->getFirstName() . " " . $c->getLastName();

It returns the relevant row.

Link to comment
Share on other sites

Ignore the last post, my code now, however the save() method is not working as expected I believe due to the load() method not functioning correctly or the if statement that tests if the record exists being wrong. Any ideas?

<?php
/* MySQL Columns & Types
Id - Primary Key (Index), Auto Increment - Int (11)
Title - Varchar (20)
FirstName - Varchar (60)
LastName - Varchar (60)
*/

class client
{
    private $_mysqli;
    private $_title;
    private $_firstName;
    private $_lastName;
    private $_client_id;

    //Connect to MySQL
    public function __construct()
    {
        $this->_mysqli = new mysqli("localhost", "test", "test", "test");

        if ($this->_mysqli->error) {
            echo $this->_mysqli->error;
        }
        
    }

    //These functions build the insert query so they can be called one at a time or all at once
    public function setTitle($title)
    {
        $this->_title = $title;
    }

    public function getTitle()
    {
        echo $this->_title;
    }

    public function setFirstName($firstname)
    {
        $this->_firstName = $firstname;
    }

    public function getFirstName()
    {
        echo $this->_firstName;
    }

    public function setLastName($lastname)
    {
        $this->_lastName = $lastname;
    }

    public function getLastName()
    {
    echo $this->_lastName;
    }

    public function load($client_id)
    {
		$query = "SELECT * FROM clients WHERE id = " . $client_id;
		$sql = $this->_mysqli->query($query);
		
		if($sql->num_rows > 0) {
			$row = $sql->fetch_assoc();
	
			$this->_client_id = $client_id;
			$this->_title = $row['title'];
			$this->_firstName = $row['firstname'];
			$this->_lastName = $row['lastname'];
						
		} else {
			echo 'Client not found!';
		}
    }
    
    public function save()
    {
		$query = "SELECT * FROM clients WHERE id = " . $client_id;
		$sql = $this->_mysqli->query($query);
		
		if($sql->num_rows > 0) {
    		$query = "UPDATE clients SET title='" . $this->_title . "' firstname='" . $this->_firstName . "' lastname='" . $this->_lastName . "' WHERE id ='" . $this->_client_id . "'";
    	} else {
    		$query = "INSERT INTO mysql (id, title, firstname, lastname) VALUES (NULL, '" . $this->_title . "', '" . $this->_firstName . "', '" . $this->_lastName . "')";
   		}    		
	$mysqli->query($query);
    $sql->close();
    }
}

//Code to change the last name and update to mysql
$c = new client();
if ($c->load($client_id)) {
$c->load(3);
$c->setLastName('Smith');
$c->save();
}
Link to comment
Share on other sites

  • Solution
<?php
/* MySQL Columns & Types
Id - Primary Key (Index), Auto Increment - Int (11)
Title - Varchar (20)
FirstName - Varchar (60)
LastName - Varchar (60)
*/

class client
{
    private $_mysqli;
    private $_title;
    private $_firstName;
    private $_lastName;
    private $_client_id;

    //Connect to MySQL
    public function __construct()
    {
        $this->_mysqli = new mysqli("localhost", "test", "test", "test");

        if ($this->_mysqli->error) {
            echo $this->_mysqli->error;
        }
        
    }

    //These functions build the insert query so they can be called one at a time or all at once
    public function setTitle($title)
    {
        $this->_title = $title;
    }

    public function getTitle()
    {
        echo $this->_title;
    }

    public function setFirstName($firstname)
    {
        $this->_firstName = $firstname;
    }

    public function getFirstName()
    {
        echo $this->_firstName;
    }

    public function setLastName($lastname)
    {
        $this->_lastName = $lastname;
    }

    public function getLastName()
    {
    echo $this->_lastName;
    }

    public function load($client_id)
    {
		$query = "SELECT * FROM clients WHERE id = " . $client_id;
		$sql = $this->_mysqli->query($query);
		
		if($sql->num_rows > 0) {
			$row = $sql->fetch_assoc();
	
			$this->_client_id = $client_id;
			$this->_title = $row['title'];
			$this->_firstName = $row['firstname'];
			$this->_lastName = $row['lastname'];
			
			return true;
		} else {
			echo 'Client not found!';
		}
    }
    
    public function save()
    {
		if ($this->_client_id) {
			$stmt = "id = " . $this->_client_id;
		} else {
			$stmt = "title LIKE '" . $this->_title . "' AND firstname LIKE '" . $this->_firstName . "' AND lastname LIKE '" . $this->_lastName . "'";
		}
		
		$check = "SELECT * FROM clients WHERE $stmt"; 
		$sql = $this->_mysqli->query($check);
		//echo "Check: " . $check . "<br />";
		
		$row = $sql->fetch_assoc();
		$stmt_id = $row['id'];
		
		if($sql->num_rows > 0) {
    		$query = "UPDATE clients SET title='" . $this->_title . "', firstname='" . $this->_firstName . "', lastname='" . $this->_lastName . "' WHERE id =" . $stmt_id; 
			echo "Client Updated Successfully!<br />";
    	} else {
    		$query = "INSERT INTO clients (id, title, firstname, lastname) VALUES (NULL, '" . $this->_title . "', '" . $this->_firstName . "', '" . $this->_lastName . "')";
			echo "New Client Inserted Successfully!<br />";
   		}  		
	//echo "Query: " . $query . "<br />";
	if (!$this->_mysqli->query($query)) {
    printf("MySQL Error: %s\n", $this->_mysqli->error);
	}
    $sql->close();
    }
}

?>

My finished code for reference.

Link to comment
Share on other sites

you beat me to it, the load only assigned the data to the parameters, if you wanted to test it you needed to add return true

 

Yeah I spotted it after looking over it for a while, thanks very much for the help mate!  :happy-04:

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.