Ok so i've been reading about classes and I made my first class. I don't want to form bad habbits so I want you guys to tell me if I'm doing it right or if theres a better way to do something that I"m doing?
Code:
- <?php
- class Database {
- function __construct(){
- $dbh=mysql_connect ("localhost", "board_bobito2", "bobito2") or die ($this->sql_error());
- mysql_select_db ("board");
- }
- protected function sql_error() {
- echo mysql_error();
- }
- function do_query($query) {
- return mysql_query($query);
- }
- function get_assoc($query) {
- return mysql_fetch_assoc($query);
- }
- function get_array($query) {
- return mysql_fetch_array($query);
- }
- function get_rows($query) {
- return mysql_num_rows($query);
- }
- }
- ?>
And this is how I'm doing a query and displaying it.Code:
- <?php
- include('query.php');
- $db =new Database;
- $query =$db->do_query("SELECT * FROM support_users WHERE username='admin'");
- $row =$db->get_assoc($query);
- echo $row['username'];
- ?>
Also I'm going to create a new file for each class and it's subclasses so like all classes relating to users will be in the users.php file which is in the framework folder. Do you guys do something similar?
Yes.
http://www.cakephp.org
I just don't bother writing the nitty-gritty myself.![]()
By the way, you probably want the database connection information in its own class, and have a wrapper function for the querying.
~Artemis
Yes.
http://www.cakephp.org
I just don't bother writing the nitty-gritty myself.![]()
By the way, you probably want the database connection information in its own class, and have a wrapper function for the querying.
~Artemis
You really like cake don't you![]()
Whats a wrapper function?
Yes I do. ^_^
Basically, it'd be like creating a method of the database class called query that would just call mysql_query. It performs an already-existing function with little to no modification. The benefit is, all your calls are to this class' method, so you can update how you query things easily, and if you want to, you can easily fill in required but static fields (e.g., the host, username, password, etc.) in the method, meaning you don't have to type them hundreds of times, and get screwed when one changes.
~Artemis