Page 1 of 1

Classes in PHP and POST data

Posted: Wed Sep 19, 2007 10:46 pm
by Mr Tech
What is the best way to use post data in a class?

So for example, I have a class called 'Clients' and a function within it called 'add'. I want to submit a MySQL query using the add function within the class. A code example

Code: Select all

class Clients {

function add() {
mysql_query("insert into table values('....')");
}

}
Is it better to put the $_POST data directly into the function:

Code: Select all

class Clients {

function add() {
mysql_query("insert into table values('$_POST[a]','$_POST[b]')");
}

}
Or is it better to add the post data to the function:

Code: Select all

class Clients {

function add($a, $b) {
 mysql_query("insert into table values('$a','$b')");
}

}
Or is it better to add them as variables:

Code: Select all

class Clients {

var $a = $_POST[a];
var $b = $_POST[b];

function add() {
 mysql_query("insert into table values('$this->a',"$this-b')");
}

}
I'm pretty new with classes so I'm not sure what the best practices are....

Posted: Wed Sep 19, 2007 10:58 pm
by maliskoleather
option 2 is your best bet... pass them as function arguments.

also, be sure to escape your variables before executing the query.

what is the data of your class

Posted: Wed Sep 19, 2007 11:34 pm
by yacahuma
what is the data of your client class??

your are using php5 right?

Posted: Wed Sep 19, 2007 11:39 pm
by feyd
None of the options are great as they all lock you into specific queries. Honestly, this functionality should be apart of a database abstraction class.

Posted: Wed Sep 19, 2007 11:39 pm
by Mr Tech
Just form information...

PHP 4....

Posted: Wed Sep 19, 2007 11:43 pm
by Mr Tech
feyd wrote:None of the options are great as they all lock you into specific queries. Honestly, this functionality should be apart of a database abstraction class.
Got any recommendations of a database abstraction class? Or are they all the sale?

Even if you use a database class, wouldn't you still need to write to variables into the class? Correct me if I'm wrong.

Here's an example of what I mean. My code isn't correct, I can't remember the procedure of using a class withing another class....

Code: Select all

class Clients {

function add($a, $b) {
DB::query("insert into table values('$a','$b')");
}

}

Posted: Wed Sep 19, 2007 11:43 pm
by ReDucTor
You should stick with method 2, The reason behind this is seperation, between your class, and your input.

Code: Select all

class Clients {

function add($a, $b) {
 mysql_query("insert into table values('$a','$b')");
}

}
Your class/function doesnt and shouldnt know where the data came from, it just needs to know what the data is. The last method wont work either.

Posted: Thu Sep 20, 2007 12:04 am
by feyd
Many database abstraction classes are similar. However some are more feature rich, such as AKA Panama Jack's ADOdb Lite.