Results 1 to 8 of 8

Thread: Connect Object Help (Newbie to OOP w/ PHP)

  1. #1
    Join Date
    Apr 2009

    Connect Object Help (Newbie to OOP w/ PHP)

    Ok so I am trying to create a class that connects to mysql and runs a query. Here is the code:
    PHP Code:
    class dbConnect {
    __construct($host,$user,$passwd,$dataB) {
    $this->host $host;
    $this->user $user;
    $this->passwd $passwd;
    $this->dataB $dataB;
    connect($sql) { 
    $conn=mysql_connect($host,$user,$passwd) or die (mysql_error());
    $db=mysql_select_db($dataB,$conn) or die ("Unable to connect to database1"); 
    $result mysql_query($sql$conn) or die ("Couldn't Connect"); 

    $connect1 = new dbConnect("","example_user","example_pass","database");

    $db_query $connect1->connect("SELECT * FROM database"); 
    When I run this, I get the following error:
    "Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2)". I know that I can connect, I have done so hundreds of times, just not using the above code. I verified that the data is being passed into the class with the following code:
    PHP Code:
    print "host: {$connect1->host}<br>";
    "user: {$connect1->user}<br>";
    "password: {$connect1->passwd}<br>";
    "database: {$connect1->dataB}"
    This displays all the information as passed into the class. Any ideas why its not working?

  2. #2
    Join Date
    Aug 2004
    You want to use $this-> prepended to each class variable in the args for mysql_connect().

    PS: You might want to move the connection part either to a separate method or into the constructor, as you likely will not want to connect to the DB each time a query is requested.

    PPS: Note that unless you're doing this just for OOP practice/learning, with PHP 5 you already have OOP database classes with the MySQLi and PDO extensions.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  3. #3
    Join Date
    Apr 2009
    That I am, practicing OOP. I made the $this-> change and it does work. Could you provide an example of what you mean by moving the connection to the constructor and as a seperate method?

  4. #4
    Join Date
    Apr 2009
    also, is there a way to close the database connection in the dbconnect class after the query is run?

  5. #5
    Join Date
    Nov 2008
    Quote Originally Posted by themonkey40 View Post
    also, is there a way to close the database connection in the dbconnect class after the query is run?
    Yes, but the question is why would you want to? If you want to close the connection at all it is probably best done in the class's destructor method, but it is not generally necessary (and it is actually less efficient) to close and reopen a connection before and after each query.

    Generally you would create a connection in the class's constructor method, store the resource identifier as a class property and let PHP close the connection when the script stops execution.

    Another tip, it is usually a very good idea to create an abstract superclass which defines methods to be implemented by DBMS-specific child classes. Not only does this allow you to abstract database operations and decouple you from a particular DBMS, it also gives you a place to define common functionality.

    Here's a very simple example (I have implemented the close connection in the classes destructor as mentioned above):

    PHP Code:

    abstract class Database {
        protected abstract function 
        protected abstract function 
        protected abstract function 
        public abstract function 
        public abstract function 
        public abstract function 
    // etc
    public function __construct($host$user$pass$dbname) {
            if (!
    $this->link $this->connect($host$user$pass)) {
                throw new 
    Exception("Could not connect to $host as $user");
            if (!
    $this->selectDb($dbname)) {
                throw new 
    Exception("Could not connect select database $dbname");
        public function 
    __destruct() {

    MySqlDatabase extends Database {
        protected function 
    connect($host$user$pass) {
        protected function 
    disconnect() {
        protected function 
    selectDb($dbname) {
        public function 
    query($sql) {
        public function 
    getAssoc($resourceId) {
        public function 
    numRows($resourceId) {

    // client code:
    try {
    $db = new MySqlDatabase('localhost''root''pass''foo_db');
    } catch (
    Exception $e) {
    if (
    $result $db->query('SELECT * FROM `foo`')) {
        if (
    $db->numRows() > 0) {
            while (
    $row $db->fetchAssoc($result)) {

    The obvious benefit here is that you can create a second concrete database class, say SqlServerDatabase, and because client code knows it is an instance of Database it can be confident of the interface and safely call the classes methods. Swapping database providers then just becomes a matter of creating a SqlServerDatabase object instead of a MySqlDatabase object - client code is blissfully unaware. (This is called polymorphism in the OO world in case you weren't aware of that).
    Last edited by Mindzai; 03-04-2010 at 04:43 AM.
    The first rule of Tautology Club is the first rule of Tautology Club.

  6. #6
    Join Date
    Aug 2004
    Or for extra credit you could look into using the "decorator pattern" to control which DBMS is used, so that you would always instantiate the same main database class name.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  7. #7
    Join Date
    Apr 2009
    Mindzai, when I tried your cod, I got the following error.

    "Warning: Missing argument 1 for MySqlDatabase::numRows(), called in /Library/WebServer/Documents/Websites/flowline/new_design/code_testing_class.php on line 66 and defined in /Library/WebServer/Documents/Websites/flowline/new_design/code_testing_class.php on line 52

    Warning: mysql_numrows(): supplied argument is not a valid MySQL result resource in /Library/WebServer/Documents/Websites/flowline/new_design/code_testing_class.php on line 53"

    Not sure why?

  8. #8
    Join Date
    Nov 2008
    Well the error message is telling you why - the method expects an argument and the example code I posted doesn't provide it (I was typing directly into the forum reply box so didn't notice). I didn't really intend for you to copy and paste the code and expect it to work though, it was just an example of inheritance and polymorphism I thought might be useful since you said you were learning OOP. The point was the concept not the code itself.

    Re the decorator pattern, when I write abstraction for databases (which I don't very often any more since I discovered PDO!), it tends to be for small and simple projects so I've always found the inheritance managable. I agree that for something larger where you start to get into multiple branches of inheritance switching to a composition based approach such as decorator is a good idea.
    The first rule of Tautology Club is the first rule of Tautology Club.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center



X vBulletin 4.2.2 Debug Information

  • Page Generation 0.14733 seconds
  • Memory Usage 2,959KB
  • Queries Executed 15 (?)
More Information
Template Usage (34):
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (3)bbcode_php
  • (1)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (8)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (8)postbit
  • (8)postbit_onlinestatus
  • (8)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (73):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates