Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

conecting to db with php class

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

conecting to db with php class

Postby farhad » Tue Mar 26, 2013 5:39 am

Code: Select all
   class connect
{
   private static $_dbUser = 'admin-book';
   private static $_dbPass = '389856';
   private static $_dbDB = 'zadmin_book';
   private static $_dbHost = 'localhost';
   private static $_connection = NULL;

   /**
    * Constructor
    * prevents new Object creation
    */

   private function __construct(){
   }

   /**
    * Get Database connection
    *
    * @return Mysqli
    */

   public static function getConnection() {
      if (!self::$_connection) {
     self::$_connection = @new mysqli(self::$_dbHost, self::$_dbUser, self::$_dbPass, self::$_dbDB);
   
         if (self::$_connection -> connect_error) {
            die('Connect Error: ' . self::$_connection->connect_error);
         }
      }
      return self::$_connection;
   }
}

I had used that code and put it into file and named it db.php
then i wrote below code but it doesn't work-Thanks for any help
Code: Select all
$connection = connect::getConnection();

$result = $connection->query($query);

$query = "SELECT * from  pages";
if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($row = $result->fetch_row()) {
     
$imgsrc=$row[1];

echo '<tr><td>'.$row[0].'</td><td>'.$row[1].'</td><td>text</td><td>book1</td></tr>';
echo '</div>';         
         }
             /* free result set */
    $result->close();
}
$mysqli->close();
farhad
New php-forum User
New php-forum User
 
Posts: 2
Joined: Tue Mar 26, 2013 5:29 am

Re: conecting to db with php class

Postby seandisanti » Tue Mar 26, 2013 11:48 am

Could you be more specific as to what's going on when it 'doesn't work'. Is it returning an error? If so, what error? Here's the Database.php that I typically use. it is using PDO, (faster and more secure than mysql_ or mysqli_ functions). The connection parameters are declared in a constants.php, and this class is loaded as necessary from an autoloader in another file.It is very easy to implement though, and then just call $db = Database::getInstance(); and you have a new PDO object and all of the functionality that offers.
Code: Select all
<?php
/*
 * Database class only one connection is allowed.
 */

class Database extends PDO{

    private 
$connection;
    private static 
$instance;

    public static function 
getInstance() {
        if (!
self::$instance) {
            
            
self::$instance = new self("mysql:host="DBHOST ";dbname=".DB,DBUSER,DBPASSWORD);
        }
        return 
self::$instance;
    }

    
/*
     * empty clone magic method to prevent duplication
     *
     */

    
private function __clone() {

    }

    public function 
getConnection() {
        return 
$this->connection;
    }

}
 
seandisanti
php-forum Fan User
php-forum Fan User
 
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: conecting to db with php class

Postby farhad » Tue Mar 26, 2013 10:07 pm

thanks for your help ,problem solved-
just one thing that I couldn't get:
It works whether the below code is written or not in connect class
so what's this code's operation?
Code: Select all
 private function __construct() {
   }

regard
farhad
New php-forum User
New php-forum User
 
Posts: 2
Joined: Tue Mar 26, 2013 5:29 am

Re: conecting to db with php class

Postby seandisanti » Wed Mar 27, 2013 10:02 am

well that declaration is an invalid one. __construct is a magic method that runs when an object of a class is instantiated. but as a magic method, it is public static rather than private, but you only really need to write 'function __construct(){}' because as a magic method the access level is already predetermined. When you are instantiating an object that has properties that need to be set, the __construct() method is the place to do that, or to call an initialization method. Here's an example of a typical constructor i use in a lot of classes.
Code: Select all


    
function __construct($data = array()) { //receives an array of data to populate the parameters
        
if (!is_array($data) == TRUE) {
            return 
false//returns false if array isn't passed
        
}
        if (
count($data) > 0) {//step through the array
            
foreach ($data as $name => $value) {
                
$this->__SET($name$value);//my __set function verifies that the property exists, and sets it to the passed value if it does
            
}
        }
        
$db Database::getInstance();
        if (isset(
$this->id)){//assuming the object was instantiated from an array so already exists in db
            
$sql "SELECT 
                        t.descr as title,
                        l.descr as location,
                        concat_ws(' ',u.first_name,u.last_name) as reports_to,
                        d.descr as department, 
                        st.descr as status 
                    FROM 
                    job j inner join job_locations l ON j.location_id=l.id 
                    INNER JOIN job_departments d on j.department_id=d.id 
                    INNER JOIN users u on j.reports_to_id = u.id 
                    INNER JOIN job_titles t ON j.title_id = t.id 
                    INNER JOIN job_status st ON j.status_id = st.id
                    WHERE j.id=" 
$db->quote($this->id);
            
$result $db->query($sql);
            if (!
$result || $result->rowCount()==0){
                return 
false;//no records found
            
}//this sets the relevant properties based on the result of the query above
            
$results=$result->fetch(PDO::FETCH_ASSOC);
            
$this->title $results['title'];
            
$this->department $results['department'];
            
$this->location $results['location'];
            
$this->reports_to $results['reports_to'];
            
$this->status $results['status'];
        }
        return 
$this;//$this is now a valid object with all fields populated.  give it back
        
    
}
 
seandisanti
php-forum Fan User
php-forum Fan User
 
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm


Return to PHP coding => General

Who is online

Users browsing this forum: Bing [Bot] and 2 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron