Jump to content

Trying to convert my existing code to an OOP framework.


p2bc

Recommended Posts

I am converting my existing code to a more friendly version for PHP5, and since commands like "mysql_real_escape_string" are being deprecated, I figured I would embrace OOP fully moving forward.

 

The problem I am having is the "nesting" of OOP commands.

 
$db_connection = new mysqli("localhost","db_user","db_pw","db_name");
 
if(mysqli_connect_errno()){
  printf("Connection fails: %s\n", mysqli_connect_error());
}

$username = $db_connect->real_escape_string($_POST['username']);
 
$stmt = $db_connection->stmt_init();
 
....
and so on
 
 

The problem I am having happen when I want to take it one step further and put all that in a class.

class Make_Connection {


   pivate $db_connection
 
   function __construct(){
      $this->make_connection();
   }
 
   public function make_connection(){
      $this->db_connection = new mysqli("localhost","db_user","db_pw","db_name");
      if(!$this->db_connection){
          die("Databse connction failed: %s\n", mysqli_connect_error());
      } else {
          $stmt = $this->db_connection->stmt_init()                  <===========This does not work obviously.
          ...
      }
   }
 
   public function clean_sql($value){
      $value = $this->db_connection->real_escape_string($value)      <===========This does not work obviously.
   } 
 
 
}
 
$db = new Make_Connection();

Now I know I need "$this" the reference a variable within itself, because this works just fine:

   public function make_connection(){

      $this->db_connection = mysqli_connection("localhost","db_user","db_pw","db_name");

      if(!$this->db_connection){

          die("Databse connction failed: %s\n", mysqli_error());

      } else {

          $db_select  = mysqli_select_db($this->dbconnection, "db_name");
          if(!$db_select){
             die("Databse selction failed: %s\n", mysqli_error());
          }

      }

   }

Even if I left this part untouch it does not help with the "real_escape_string()". As well, like I said I want to make this most current moving forward, so I would like to impliment the stmt_init() command.

 

I belive it comes down to syntax, if I am wrong please do excuse me. I tried serveral variation, including $this->db_connection::real_escape_strig(), all of them wrong of course.

 

So if someone could clarify where I went wrong, or point me to the correct direction I would be greatful.

 

 

Thanks all the same in advance.

Link to comment
Share on other sites

I was getting:

 

Notice: Undefine poperty: Make_Connection::$db_connect in /var/www/include/database.class on line 17

 

After your reply I went back and reviewed my code, and I am truely embaraced to say it is a "typo" error I switch from "db_connect" to "db_connection".

 

I changed it $this->db_connection->real_escape_string($value) and it worked

 

 

Got to say Humble Pie really doesn't taste good, but I totally derve it.

 

Sorry for the trouble, and thank you for the help.

Link to comment
Share on other sites

I feel so bad for wasting eveyone's time, I figure I would add my code as it is so far, that works, so that if anyone else is looking for something similar, they would have a point of reference.

 

Others a welcome to cretic it. There is room for improvement, but this it just th initial port of my code.

 

SQL for the Database:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(15) NOT NULL,
  `password` varchar(25) NOT NULL,
  `first_name` varchar(15) NOT NULL,
  `last_name` varchar(15) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

INSERT INTO `users` (`id`, `username`, `password`, `first_name`,
`last_name`) VALUES (1, 'p2bc', 'mypwd', 'John', 'Smith');

config file to store the database variables (/include/config.php):

<?php
    //Define the constants if they are not already defined.
    defined("DB_SERVER")     ? NULL : define("DB_SERVER", "localhost");      // Server location
    defined("DB_USER")         ? NULL : define("DB_USER","sample_db_user");     // The user specifically setup to access this database.
    defined("DB_PASSWORD")     ? NULL : define("DB_PASSWORD","super_secret_pw");   // Password for the user of this database.
    defined("DB_NAME")         ? NULL : define("DB_NAME","sample_db");   // Nme of the database
?>

The database class that handles the connection to the databse and retreaving information (/include/database.class)

<?php
    require_once("config.php");  

    class MySQLDatabase {

        private $db_connection;
        private $db_stmt;
                
        function __construct(){
            $this->open_connection();
        }

        public function open_connection(){
            $this->db_connection = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
            if(!$this->db_connection){
                die("Database connection failed:" . mysqli_error());
            } else {
                $this->db_connection->select_db(DB_NAME);
                if(!$this->db_connection->select_db(DB_NAME)){
                    die("Database selection failed:" . mysqli_error());
                }
            }
        }

        public function close_connection(){
            if(isset($this->db_connection)){
                mysqli_close($this->db_connection);
                unset($this->db_connection);
            }
        }

        public function prep_statement($sql){
            $this->stmt = $this->db_connection->stmt_init();
            $search_term = $this->escape_value($search_term);
            if ($this->stmt->prepare($sql)){
                $stmt->bind_param("s",$search_term);
                $this->stmt->execute();
                $stmt->bind_result($this->db_query_result);
                $stmt->fetch();
                $stmt->close();
            }
        }

        private function prep_stmt($sql,$term=NULL){
            $this->stmt = $this->db_connection->stmt_init();
            if ($this->stmt->prepare($sql)){
                if(!$term == NULL){
                    $search_term = $this->escape_value($term);
                    $this->stmt->bind_param("s",$search_term);
                }
                $this->stmt->execute();
            }
        }

        public function query($sql,$term=NULL){
            $this->prep_stmt($sql,$term);
            $this->stmt->bind_result($query_result);
            $this->stmt->fetch();
            return $query_result;
            $stmt->close();
        }

        public function fetch_array($sql,$term=NULL){
            $this->prep_stmt($sql,$term);
            $this->stmt->bind_result($key,$value);
            $this->stmt->close;
        }

        public function num_rows($sql,$term=NULL){
            $this->prep_stmt($sql,$term);
            $this->stmt->store_result();
            return $this->stmt->num_rows;
            $this->stmt->close;
        }
         
        public function insert_id($sql,$term=NULL){
            $this->prep_stmt($sql,$term);
            $this->stmt->store_result();
            return $this->stmt->insert_id;
            $this->stmt->close;
        }
        
        public function affected_rows($sql,$term=NULL){
            $this->prep_stmt($sql,$term);
            $this->stmt->store_result();
            return $this->stmt->affected_rows;
            $this->stmt->close;
        }
    
        public function escape_value($term){
            $term = $this->db_connection->real_escape_string($term);
            return $term;
        }
    }


    $database = new MySQLDatabase();

?>

The actual basic page that is displayed to the user (/public/index.php). Not pretty, just functional.

<?php
    require_once("../includes/database.class");

    $var = $_POST['username'];

    $sql1 = "SELECT `first_name` FROM `users` WHERE username=?";
    $sql2 = "SELECT username FROM users WHERE first_name='John'";

    echo ($database->query($sql1,$var));
    echo ($database->query($sql2));
    echo ($database->affected_rows($sql2));
    echo ($database->num_rows($sql2));
    echo ($database->insert_id($sql2));
?>

All these folders and files are placed in a folder, and the DNS lookup points to the public folder within that folder. (www.example.com = /var/www/site/public)

 

What I like about the code as I have it setup, you can use the same command ($database->query()) to run different type qury strings. which addes to it modularity.

 

 

Thanks for your time.

Edited by p2bc
Link to comment
Share on other sites

@ignace   I will let you in on a little secret. I take offence you your statement. Not only do I "re-invent the wheel" every day professionally, where would we be as a society if people didn't question and go against convention. Most technological advancements we enjoy are from people who re-invent the wheel, or do you actually think Apple invented the "tablet".

 

For that matter there would not be anything called ruby, or PHP if people did not challenge and re-invent things, improving upon things that came before. We would all be coding in basic and C.

 

But to answer you question specifically, I like it. Why does anyone tinker with their cars in their garages on the weekend, when there are mechanics out there. Why are any of us here on these forums, because we like to tinker, and do things ourselves. And if someone happens to come up with a piece of code that is note worthy and goes again convention, I say good on them.

 

Not that I think my code that I posted is note worthy, on the contrary. It is pretty basic.

 

 

 

 

 

 

I will get off my soap box now, and apologize to everyone else for my rant.  ;D

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.