Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > PHP/MySQL > PHP Databases
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
PHP Databases Using PHP in conjunction with databases. PHP questions not specific to databases should be directed to one of the other PHP forums.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the PHP Databases section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old May 12th, 2008, 04:19 PM
Registered User
 
Join Date: May 2008
Location: , , .
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default review my code

Hello everyone, I am new to php and mysql so I figured making my own custom forums would be the perfect excercise to learn about the two topics. I have a rudimentary board setup and now I want to start getting feedback about how lame and unsecure it is. Instead of posting all my code I am only going to post the code for my php class Database, which encapsulates the mysql database and provides all functionality for interacting with it. If you have the time please give me some feedback on what I could improve on it.

Code:
<?php 
session_start();
class Database {

   /**
    * database users is shown as a table
    */
    const USER_TABLE_ATTRIBUTE = "user list";

   /**
    * database forum is shown as a table
    */
    const FORUM_TABLE_ATTRIBUTE = "forum list";

   /**
    * contains current table attribute
    */
    const FORUM_TABLE_ATTRIBUTE_TOPIC = "topic list";
 
   /**
    * Using a singleton pattern, only one instance should ever exist
    */
    private static $SINGLETON;

   /**
    *private constructor used to enforce the singleton pattern
    */
    public function __construct(){}

   /**
    * 
    */
    private $database;

   /*
    * The database connection
    */
    private $con;

   /**
    * Username of database owner
    */
    private $owner;

   /**
    * MySQL Password
    */
    private $password;

   /**
    * address where sql server is
    */
    private $address;

   /**
    * used to get the one and only instance
    */
    public static function instance(){
        if(!isset(self::$SINGLETON)){ 
              self::$SINGLETON = new Database();
        }
        return self::$SINGLETON;
    }

   /**
    * enforce singleton
    */
    private function _clone(){}

   /**
    * connects the forums to the sql server
    */
    public function connectToSQLServer(){

        $this->con = mysql_connect("localhost","db","dbpassword");
        if(!$this->con) die('Could not connect: ' . mysql_error());
        //this.selectDatabase();
    }

   /**
    * connects the forum to a database, currently only one database supported
    */
    public function selectDatabase(){
        mysql_select_db("forum", $this->con);
    }

   /**
    * Used to add a user
    */
    public function addUser($userName,$firstName,$lastName,$password,$email,$newsLetter,$avatar){

        //protect against mysql injection attacks
        mysql_real_escape_string($userName);
        mysql_real_escape_string($firstName);
        mysql_real_escape_string($lastName);
        mysql_real_escape_string($password);
        mysql_real_escape_string($newsLetter);
        mysql_real_escape_string($avatar);

        $encrypted_password = crypt($password,"WJjpBndDfO8675");

        $date = date("Y-m-d");

        $result = mysql_query("INSERT INTO users (userName,lastName,firstName,email,created,password,avatar) 
                               VALUES ('$userName', '$lastName', '$firstName','$email','$date','$encrypted_password','$avatar')");
        //if($newsLetter) $result2 = mysql_query("INSERT INTO newsLetterSubscribers VALUES ('$email')");
        echo mysql_error();
        return $result;
    }

   /**
    * login
    */
    public function login($user,$password){
        $encrypted_password = crypt($password,"4388WJjpBndDfO");
        if(1 == mysql_num_rows($result = mysql_query("SELECT * from users WHERE userName='$user' and password = '$encrypted_password'"))){
            $_SESSION['user']=$user;
            $_SESSION['logged_in']=true;

            //get privelege level
            $result = mysql_query("SELECT privilegeLevel from users WHERE userName='$user' and password = '$encrypted_password'");
            $row = mysql_fetch_array($result);
            $_SESSION['user_privilege_level'] = $row[0];
            return true;
        }
        else {
            $_SESSION['logged_in']=false;
            //$_SESSION['incorrect_login']=true; 
            if (empty($result)){
                echo mysql_error();
            }
            return false;
        }

    }

    public function userNameAvailable($userName){

        //protect against mysql injection attacks
        mysql_real_escape_string($userName);
        //echo ">>>".$userName;
        $result = mysql_query("SELECT userName FROM users WHERE userName='$userName'");

        while($row = mysql_fetch_array($result)){

            if((strcmp(strtolower($row['userName']),strtolower($userName)))==0){  //converts each to lowercase then compares with strcmp()
                return false;
            }
        }


    return true;
    }

   /**
    * runs a query and returns the result
    *TODO: security check
    */
    public function runQuery($query){
        return mysql_query($query);
    }

   /**
    * add topic into forum
    *TODO: verify security of $message, since it is being plugged into an sql query
    */
    public function addTopic($subject,$message,$forum){

        //filter_var($message,FILTER_SANITIZE_SPECIAL_CHARS);
        switch($forum){
            case 1:
                mysql_query("insert into general (userName,topic) 
                             values (\"".$_SESSION['user']."\",\"".$subject."\");");
                //now get tid of the topic just inserted
                $result = mysql_query("select TID from general where topic=\"".$subject."\";");
                while($row = mysql_fetch_array($result)){ $tid = $row['TID'];}
                mysql_query("insert into posts (TID,message,FID,userName) 
                             values (\"".$tid."\",\"".$message."\",\"1\",\"".$_SESSION['user']."\");");

                break;
            default:
                return false;
        }

        return true;
    }

   /**
    * add a reply to a topic
    */
    public function addReply($message,$tid,$fid){
        switch($fid){
            case 1:
                mysql_query("insert into posts (TID,message,FID,userName) 
                             values (\"".$tid."\",\"".$message."\",\".$fid.\",\"".$_SESSION['user']."\");");
                break;
            default:
                return false;
        }

        return true;
    }

   /**
    * Get visual proxy for a query, defaults to a table
    * this will actually build the web page here
    */
    public function visualProxy($query,$attribute){
        $result = $this->runQuery($query);

        if(strcmp($attribute,self::USER_TABLE_ATTRIBUTE)==0){
            echo "<table border = 1>
                      <tr>
                        <td>User Name</td>
                        <td>First Name</td>
                        <td>Last Name</td><td>EMAIL</td>
                        <td>Date Created</td>
                        <td>Privelege Level</td>
                        <td>Password</td>
                    </tr>";

            while($row = mysql_fetch_array($result)){

                echo "<tr>".
                    "<td>".$row['userName']."</td>".
                    "<td>".$row['firstName']."</td>".
                    "<td>".$row['lastName']."</td>".
                    "<td>".$row['email']."</td>".
                    "<td>".$row['created']."</td>".
                    "<td>".$row['privilegeLevel']."</td>".
                    "<td>".$row['password']."</td>";
                echo "</tr>";
            }
            echo "</table>";
        }
        else if(strcmp($attribute,self::FORUM_TABLE_ATTRIBUTE)==0){

            echo "<table class=\"table\" border=\"0\" cellpadding=\"5\" class=\"forumline\" cellspacing=\"0\" width=\"100%\">
                      <tr>
                        <td class=\"heading\"  width=\"10\">&nbsp</td>
                        <td class=\"heading\"  width=\"120\">User Name</td>
                        <td class=\"heading\">Topic</td>
                        <td class=\"heading\" width=\"80\">Replies</td>
                        <td class=\"heading\" width=\"80\">Views</td>
                        <td class=\"heading\" width=\"80\">Last Post</td>
                    </tr>";

            while($row = mysql_fetch_array($result)){

                if($class == "row1") $class = "row2";
                else $class = "row1";

                //get forum id
                $temp = mysql_fetch_array(mysql_query("select FID from posts where TID=\"".$row['TID']."\""));
                $fid=$temp[0];

                //get date user joined
                $temp = mysql_fetch_array(mysql_query("select created from users where userName=\"".$row['userName']."\""));
                $joined=$temp[0];

                //get avatar
                $temp = mysql_fetch_array(mysql_query("select avatar from users where userName=\"".$row['userName']."\""));
                $avatar=$temp[0];

                //get message
                //echo "select message from posts where TID=\"".$row['TID']."\" and userName=\"".$row['userName']."\""; 
                $temp = mysql_fetch_array(mysql_query("select message from posts where TID=\"".$row['TID']."\" and userName=\"".$row['userName']."\""));
                $message=$temp[0];

                //create table
                echo "<tr>";
                $i=0;
                if($_SESSION['user_privilege_level'] == 1){
                    echo "<td class=\"".$class."\">";
                    echo "<form name=\"".$i."\" method=\"get\" action=\"administration.php\">";
                    echo "<select name=\"commands\">";
                    echo "<option value=\"dropTopic\" selected=\"selected\">drop</option>";
                    echo "<option value=\"lock\">lock</option>";
                    echo "<option value=\"unlock\">unlock</option>";
                    echo "</select>";
                    echo "<input type=\"hidden\" name=\"TID\" value=\"".$row['TID']."\">";
                    echo "<input type=\"hidden\" name=\"FID\" value=\"".$fid."\">";
                    echo "<input type=\"submit\" value=\"Apply\">";
                    echo "</form></td>";
                    $i++;
                }
                else {
                    echo "<td class=\"".$class."\"></td>";
                }
                echo "<td class=\"".$class."\" align=\"center\"><b>".$row['userName']."</b><br /><br />";
                echo "<img src=\"".$avatar."\"></img><br /><br />";
                echo "Joined: ".$joined."";
                echo "</td>";
                if($row['locked']){
                    echo "<td class=\"".$class."\" align=\"center\">";
                    echo "<a href=\"viewTopic.php?tid=".$row['TID']."&fid=".$fid."&l=".$row['locked']."\">".$row['topic'];
                    echo "[LOCKED]"."</a><br />";
                }
                else{
                    echo "<td class=\"".$class."\" align=\"center\">";
                    echo "<a href=\"viewTopic.php?tid=".$row['TID']."&fid=".$fid."&l=".$row['locked']."\">".$row['topic']."</a><br />";
                }
                echo "<div class=\"terms\">".$message."</div>";
                echo "</td>";
                echo "<td class=\"".$class."\">".$count[0]."</td>";
                echo "<td class=\"".$class."\">".$row['views']."</td>";
                echo "<td class=\"".$class."\">0</td>";
                echo "</tr>";
                //$class = "row2";

            }

            echo "</table>";

        }
    else if(strcmp($attribute,self::FORUM_TABLE_ATTRIBUTE_TOPIC)==0){
            echo "<table border=\"0\" cellpadding=\"5\" class=\"forumline\" cellspacing=\"0\" width=\"100%\">
                      <tr>
                        <td class=\"heading\"  width=\"10\">&nbsp</td>
                        <td class=\"heading\"  width=\"100\">Author</td>
                        <td class=\"heading\">Message</td>
                    </tr>";


            while($row = mysql_fetch_array($result)){
                if($class == "row1") $class = "row2";
                else $class = "row1";

                //get date user joined
                $temp = mysql_fetch_array(mysql_query("select created from users where userName=\"".$row['userName']."\""));
                $joined=$temp[0];

                //get avatar
                $temp = mysql_fetch_array(mysql_query("select avatar from users where userName=\"".$row['userName']."\""));
                $avatar=$temp[0];

                //get forum id
                $temp = mysql_fetch_array(mysql_query("select FID from posts where TID=\"".$row['TID']."\""));
                $fid=$temp[0];

                echo "<tr>";
                $i=0;
                if($_SESSION['user_privilege_level'] == 1){
                    echo "<td class=\"".$class."\">";
                    echo "<form name=\"".$i."\" method=\"get\" action=\"administration.php\">";
                    echo "<input type=\"hidden\" name=\"TID\" value=\"".$row['TID']."\">";
                    echo "<input type=\"hidden\" name=\"FID\" value=\"".$fid."\">";
                    echo "<input type=\"hidden\" name=\"commands\" value=\"dropPost\">";
                    echo "<input type=\"submit\" value=\"Remove\">";
                    echo "</form></td>";
                    $i++;
                }
                else {
                    echo "<td class=\"".$class."\">&nbsp</td>";
                }
                echo "<td class=\"".$class."\" valign=\"top\">".$row['userName']."<br />";
                echo "<img src=\"".$avatar."\"></img><br /><br />";
                echo "Joined: ".$joined."";
                echo "</td>";
                echo "<td class=\"".$class."\">".$row['message']."</td>";
                echo "</tr>";
                //$class = "row2";
            }

            echo "</table>";
        }
    }
}

?>
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Code review tool madhukp ASP.NET 1.0 and 1.1 Professional 0 March 24th, 2006 01:54 AM
Code for review advice, is there a hole? mat41 Classic ASP Professional 0 February 10th, 2006 08:16 AM



All times are GMT -4. The time now is 10:01 PM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.