www.webdeveloper.com
Results 1 to 5 of 5

Thread: [RESOLVED] How can I pass an object into PDO?

  1. #1
    Join Date
    Jan 2014
    Posts
    4

    resolved [RESOLVED] How can I pass an object into PDO?

    I'm new to php and am trying to learn oop. I have a simple input that passes the text to a class to sanitize it. I want to be able to insert the text into the database using pdo. I'm not sure if I'm going the correct way with this.

    Code:
    $sanitize = new SanitizeText($category);
    //I want the sanitize text in the database.
    $newdb = new Database();
    Code:
    class Database {
    	private $db_user = 'root';
    	private $db_password = 'password';
    	private $db_name = 'test';
    	private $db_host = 'localhost';
    	
    	public $prepare_sql;
    	public $execute_sql;
    
    	// Connect to database
    	public function __construct() {
    		try {
    			new PDO('mysql:host=' .$this->db_host. '; dbname=' .$this->db_name, $this->db_user, $this->db_password);
    			echo "Connected to database"; 
    		}
    		catch (PDOException $e) {
    			echo "Could not connect to database";	
    		}
    	}
    	
    	// Insert data.. not sure if this is proper
    	public function create() {
    
    		$stmt = $this->prepare($prepare_sql);
    		$stmt->execute($execute_sql);
    		
    	}
    }

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,399
    Well, my first thought is that if you are going to use prepared statements and bound parameters with PDO (which is a very good thing), then you should have no issues with sanitizing values for SQL use. Therefore, the only thing you would need your SanitizeText class is for issues not related to SQL/database stuff. If that's the case, then I would not inject that dependency into your Database class, as you want classes to stay narrowly focused on their specific purposes.

    If your SanitizeText class is designed for other things (e.g. screening out link or JavaScript injection), that would probably better fit wherever you would do things like form validation and so forth, not in your database class.

    If we set all that aside and assume for now that you do have a reason for using that class within your Database class, probably the best way to make that dependency obvious is to inject it directly via the constructor. That way any client code "knows" it has to provide it.

    Oh, and a database class can be a good opportunity to make use of inheritance.
    PHP Code:
    <?php

    class Database extends PDO
    {
        private 
    $sanitize;
        private 
    $db_user 'root';
        private 
    $db_password 'password';
        private 
    $db_name 'test';
        private 
    $db_host 'localhost';
        
        public function 
    __construct(SanitizeText $sanitize)
        {
            
    $this->sanitize $sanitize;
            
    parent::__construct(
                
    'mysql:host=' .$this->db_host.'; dbname='.$this->db_name,
                
    $this->db_user,
                
    $this->db_password
            
    );
        }
        
        public function 
    doSomethingWith($text)
        {
            
    $text $this->sanitize->someMethod($text);
            echo 
    "And the sanitized text is:".PHP_EOL.$text;
        }
    }
    Possible instantiation:
    PHP Code:
    $db = new Database(new SanitizeText()); 
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Jan 2014
    Posts
    4
    Thanks for replying. Maybe I explained it wrong. I'm not sure how to prepare and execute the sanitized text with PDO.

    Form text input goes to add-category.php. This includes the sanitize class to sanitize the text and the database class to update the database.
    Code:
    require 'class-database.php';
    require 'class-sanitize-text.php';
    
    // Category input text value
    $category = $_POST['category'];
    
    // Create new object to sanitize text
    $sanitize = new SanitizeText($category);
    
    $newdb = new Database();
    
    //Not sure how to actually prepare and execute the new sanitized object so I can add it to the database
    Code:
    //class-sanitize-text.php
    /* Sanitize string text */
    class SanitizeText {
    	public $SanitizeText;
    	
    	public function __construct($SanitizeText) {
    		$this->SanitizeText = filter_var($SanitizeText, FILTER_SANITIZE_STRING);
    	}
    }
    Same as previous initial post. I'm trying to get this class to only connect, read, update, delete data from the database.
    Code:
    //class-database.php
    class Database {
    	private $db_user = 'root';
    	private $db_password = 'password';
    	private $db_name = 'test';
    	private $db_host = 'localhost';
    	
    	public $prepare_sql;
    	public $execute_sql;
    
    	// Connect to database
    	public function __construct() {
    		try {
    			new PDO('mysql:host=' .$this->db_host. '; dbname=' .$this->db_name, $this->db_user, $this->db_password);
    			echo "Connected to database"; 
    		}
    		catch (PDOException $e) {
    			echo "Could not connect to database";	
    		}
    	}
    	
    	// Insert data.. not sure if this is proper
    	public function create() {
    
    		$stmt = $this->prepare($prepare_sql);
    		$stmt->execute($execute_sql);
    		
    	}
    }

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,399
    What I suggest doing is to make use of PDO's ability to use bound parameters in prepared statement. When you do that, PDO takes care of any needed sanitizing all by itself -- you don't need any SQL-related sanitizing functions (untested):
    PHP Code:
    <?php
    class Database extends PDO
    {
        private 
    $db_user 'root';
        private 
    $db_password 'password';
        private 
    $db_name 'test';
        private 
    $db_host 'localhost';
        
        public function 
    __construct()
        {
            
    parent::__construct(
                
    'mysql:host=' .$this->db_host.'; dbname='.$this->db_name,
                
    $this->db_user,
                
    $this->db_password
            
    );
        }
        
        
    /**
         * Run a query that uses bound parameters
         * @return PDOStatement
         * @param  string $sql
         * @param  array  $data
         */
        
    public function runQuery($sql, Array $data=null)
        {
            
    $stmt $this->prepare($sql);
            if(
    $stmt == false) {
                throw new 
    Exception(array_merge($this->errorInfo(), array('sql' => $sql)));
            }
            if(
    $stmt->execute($data) == false) {
                throw new 
    Exception(array_merge($stmt->errorInfo(), array('sql' => $sql)));
            }
            return 
    $stmt;
        }
    }

    // SAMPLE USAGE:

    $db = new Database();
    // note leading ":" character in parameter names in following 2 commands:
    $sql "SELECT * FROM some_table WHERE foo=:value_1 AND bar=:another_value";
    $data = array(
        
    ':value_1'       => $_GET['some_field'],
        
    ':another_value' => $_GET['another_field']
    );
    // you don't have to worry about sanitizing SQL, as PDO takes care of it for you
    $stmt $db->runQuery($sql$data);
    while(
    $row $stmt->fetch(PDO::FETCH_ASSOC)) {
        
    // do stuff with values in $row
    }
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  5. #5
    Join Date
    Jan 2014
    Posts
    4
    Thanks for the help. That helped clear it up.

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



Recent Articles