SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Guru
    Join Date
    Nov 2002
    Location
    Dubai
    Posts
    714
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Wrapping reusable code in a class

    I still consider myself to be a newbie. I always thought that I was not the programming type and did not have the guts to start coding till I laid my hands on Kevin Yank's book. I went through the book. It was so good. There were some chapters which I found difficult to understand but still managed to read most of it and also managed to make a telephone directory based on the examples given in it. Now I have purchased Harry Fueck's book and am trying out the examples in it. The book is great I am in chapter 3 where the author has explained how the basic connection method can be packaged in a function or class so it can be reused. I wrote the function and reused it in many of my codes. It saves so much time.
    But now I am stuck with the class. I copied the file "Database/MySQL.php" Then I included the class in my code in the following manner. (I am trying this out in the code for adding a joke which I have taken from Kevin Yank's book.)

    I apologise for the long code.

    Database-MySQL.php

    PHP Code:
    <?php>
    /**
    * MySQL Database Connection Class
    * @access public
    * @package SPLIB
    */
    class MySQL {
    /**
    * MySQL server hostname
    * @access private
    * var string
    */
    var $host;
    /**
    * MySQL Username
    * @access private
    * @var string
    */
    var $dbUser;
     
    /**
    * Name of database to use
    * @access private
    * @var string
    */
    var $dbName;
     
    /**
    * MySQL Resource link identifier stored here
    * @access private
    * @var string
    */
    var $dbConn;
     
    /**
    * Stores error messages for connection errors
    * @access private
    * @var string
    */
    var $connectError;
     
    /**
    * MySQL constructor
    * @param string host (MySQL server hostname)
    * @param string dbUser (MySQL User Name)
    * @param string dBPass (MySQL User Password)
    * @param string dbName (Database to select)
    * @access public
    */
     
    function MySQL($host$dbUser$dbName)
    {
         
    $this->host $host;
         
    $this->dbUser $dbUser;
         
    $this->dbName $dbName;
         
    $this->connectToDb();
    }
     
    /**
         * Establishes connection to MySQL and selects a database
         * @return void
         * access private
         */
        
    function connectToDb()
        {
         
    // Make connection to MySQL server
         
    if (!$this->dbConn = @mysql_connect($this->host,
             
    $this->dbUser$this->dbPass)) {
            
    trigger_error("Could not connect to server');
            
    $this->connectError = true;
         // Select database
         } else if (!@mysql_select_db(
    $this->dbName,$this->dbConn)) {
         trigger_error('Could not select database');
            
    $this->connectError = true;
         }
    }
     
    /**
        * Checks for MySQL errors
        * return boolean
        * @access public
        */
    function isError()
    {
         if (
    $this->connectError) {
         return true;
         }
         
    $error = mysql_error($this->dbConn);
         if (empty(
    $error)) {
         return false;
         } else {
         return true;
         }
    }
    ?>
    I tried to include the above class in the body of my code for adding jokes in the following way.

    PHP Code:
    <?php 
    // Include the MySQL class
    require_once 'Database-MySQL.php';

    $host   'localhost'// Hostname of MySQL server
    $dbUser 'root';      // Username for MySQL
    $dbName 'jokes';     // Database name
    // Connect to MySQL
    $db = &new MySQL($host$dbUser$dbName); // This is line 15
    if (isset($_GET['addjoke'])) 

    ?> 
    <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> 
    <p>Type your joke here:<br /> 
    <textarea name="joketext" rows="10" cols="40" wrap> 
    </textarea><br /> 
    <input type="submit" name="submitjoke" value="SUBMIT" /> 
    </p> 
    </form> 
    <?php 
    }
        
    if (
    $_POST['submitjoke'] == "SUBMIT") { 
        
    $sql "INSERT INTO jokes SET JokeText='".$_POST['joketext']."', JokeDate=CURDATE()"
       
        if (@
    mysql_query($sql)) { 
            echo(
    "<p>Your joke has been added.</p>"); 
        } else { 
            echo(
    "<p>Error adding submitted joke: " mysql_error() . "</p>"); 
        } 

    echo(
    "<p> Here are all the jokes in our database:" "</p>"); 
    $result = @mysql_query("SELECT JokeText FROM jokes"); 
    if (!
    $result) { 
        echo(
    "<p>Error performing query: " mysql_error() . "</p>"); 
        exit(); 

    while ( 
    $row mysql_fetch_array($result) ) { 
        echo(
    "<p>" $row["JokeText"] . "</p>"); 

    echo(
    "<p><a href='".$_SERVER['PHP_SELF']."?addjoke=1'>" "Add a Joke!</a></p>"); 
    ?> 
    </blockquote>
    I am getting an error like this.

    Parse error: parse error, unexpected $end in Database-MySQL.php on line 99 (this is the last line of the code)

    Fatal error: Cannot instantiate non-existent class: mysql on line 15

    I know that I am missing out something very crucial. Can anyone please help me. How do I include the class? I have an include file like this.
    PHP Code:
    <!-- include-me.php -->
    <?php
    function &connectToDb($host$dbUser$dbName

    // Make connection to MySQL server
    if (!$dbConn = @mysql_connect($host$dbUser)) {
         return 
    false;
    }
    // Select the database
    if (!@mysql_select_db($dbName)) {
         return 
    false;
    }
    return 
    $dbConn;
    }
     
    $host 'localhost'// Hostname of MySQL server
    $dbUser 'root';     // Username for MySQL
    $dbName 'jokes';     // Database name
     
    ?>
    I tried using the include file in my file and then added the line,
    // Connect to MySQL
    $dbConn = &connectToDb($host, $dbUser, $dbName);

    But that does not help. Where am I going wrong? As I told you earlier, my code worked when I just used the above line and the include file ie before I started working with the Database-MySQL.php. I think I lack a basic understanding of how to use this file.

  2. #2
    SitePoint Member
    Join Date
    Sep 2004
    Location
    UK
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your missing a bracket at the end of your database class. Add a '}' before the line that reads '?> ' and that should do it.

  3. #3
    SitePoint Wizard mark_W's Avatar
    Join Date
    Mar 2004
    Location
    West Midlands, United Kingdom
    Posts
    2,631
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    whenever you get a Parse error: parse error, unexpected $end then look for missing brackets! more of then than not they are the source of the problem!

  4. #4
    SitePoint Guru
    Join Date
    Nov 2002
    Location
    Dubai
    Posts
    714
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I am continuing to get the parse error even if I add } before ?>. Should the closing bracket be put in a different place?

    And why am I getting the fatal error : cannot instantiate non-existent class?

  5. #5
    SitePoint Guru
    Join Date
    Nov 2002
    Location
    Dubai
    Posts
    714
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can anyone please help me? I am quite desperate.

  6. #6
    SitePoint Guru
    Join Date
    Nov 2002
    Location
    Dubai
    Posts
    714
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    All this while, I only kept checking and rechecking for missing brackets, but I then decided to go through the full code slowly and noticed that I had put double quotes in one line in place of single quotes.
    PHP Code:
     
    // Make connection to MySQL server
    if (!$this->dbConn = @mysql_connect($this->host,
    $this->dbUser$this->dbPass)) {
    trigger_error("Could not connect to server'); 
    Notice the last line in my quote. I just removed the doublequote before Could and now my code is working.

  7. #7
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would recommend using really simple DB and Result classes like the ones below. It makes some assumptions, like passing it an array to connect and always fetching an associative array, but it is very small, portable, expandable and will work well for you.
    PHP Code:
    class DB
    {
    var 
    $link null;

    function 
    DB ($dsn=null)
    {
        if (
    $dsn) {
            
    $this->connect($dsn);
        }
    }
        
    function 
    connect ($dsn)
    {
        
    $link = @mysql_pconnect($dsn['hostspec'], $dsn['username'], $dsn['password']);
        if (
    $link) {
            
    $result mysql_select_db($dsn['database']);
        } else {
            
    $result false;
        }
        if (
    $this) {
            
    $this->link $link;
            return(
    $result);
        } else {
            
    $db = new DB();
            
    $db->link $link;
            return(
    $db);
        } 
    }
        
    function 
    disconnect ()
    {
        if (
    $db->link) {
            
    mysql_disconnect($db->link);
        } 
    }
        
    function 
    query ($sql)
    {
        return(new 
    DB_result(mysql_query($sql)));
    }
        
    function 
    isError ()
    {
        return(
    mysql_errno());
    }
        
    function 
    getMessage ()
    {
        return(
    mysql_error());
    }
        
    // end DB class


    class DB_result
    {
    var 
    $result;

    function 
    DB_result ($result=null)
    {
        
    $this->result $result;
    }
        
    function 
    fetchRow ()
    {
        if (
    $this->result) {
            return(
    mysql_fetch_assoc($this->result));
        } else {
            return array();
        }
    }
        
    function 
    numRows ()
    {
        if (
    $this->result) {
            return(
    mysql_num_rows($this->result));
        } else {
            return 
    0;
        }
    }
        
    function 
    isError ()
    {
        return(
    mysql_errno());
    }
        
    function 
    getMessage ()
    {
        return(
    mysql_error());
    }
        
    // end DB_result class

    ?> 
    And your code would look like:
    PHP Code:
    $dsn = array('hostspec'=>$host'database'=>$dbName'username'=>$dbUser'password'=>$dbPassword);
    $db =& new DB($dsn);
        
    $result $db->query("SELECT JokeText FROM jokes");
    if (
    $result->isError()) {
        echo(
    "<p>Error performing query: " $result->getMessage() . "</p>");
    } else {
        while (
    $row $result->fetchRow()) {
            echo(
    "<p>" $row["JokeText"] . "</p>");
        }


  8. #8
    SitePoint Guru
    Join Date
    Nov 2002
    Location
    Dubai
    Posts
    714
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks. I am always trying to learn and I will try out your method.

    At the moment, I am just in the process of learning about classes and also about the advantage of using classes.


Bookmarks

Posting Permissions

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