switching from mysql_ to mysqli_

Discussion in 'PHP' started by Meth_, May 21, 2010.

  1. #1
    hello all I'll try and explain my situation as throughout as possible so my apologies if I just ramble on


    I haven't created a php website in quite a few years, and back then mysql_ was the standard
    I wish to create a new website as a side project for myself but I have a predicament

    I'm used to coding in OO with php
    but connecting to a database with mysqli is different from mysql

    and I don't want the database connection to be insecure

    .... okay this is a mess I don't know how to word my question so I will show examples


    
    <?php
    
    class Db{
         
    function connect(){
    
    //connect to database, and select which db to use
    		if(!mysql_connect('localhost','username','password')) die('error');
    
    	//Select the database
    		if(!mysql_select_db('database')) die('error');
    				
    			return;
    		}
    }
    
    mysql_query("blah blah blah");
    ?>
    
    Code (markup):
    how would this be done with mysqli (pref oo style so I cau use for example $mysqli->fetch_assoc()) so i can still do queries outside of the Db class?
    I hate using $GLOBAL or whatever it's called, is there a standard way to do it?
     
    Meth_, May 21, 2010 IP
  2. Trikun3

    Trikun3 Peon

    Messages:
    28
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    If you're doing something like that, regarding using mysql in the database class and referencing it in a function outside of the object:

    <?php
    
    class Database
    {
    	public $link;
    
    	protected $host = 'localhost';
    	protected $user = 'root';
    	protected $pass = '';
    
    	protected $database = 'database_name';
    
    	public function Database()
    	{
    		$this->connect();
    	}
    
    	public function connect()
    	{
    		$this->link = mysql_connect($this->host, $this->user, $this->pass);
    		mysql_select_db($this->database, $this->link);
    	}
    }
    
    $db = new Database();
    
    $sql = "SELECT * FROM `table` LIMIT 0, 30;";
    mysql_query($sql, $db->link);
    
    Code (markup):
    For your MySQLi extension in php:

    <?php
    
    $db = new mysqli($host, $user, $pass, $database);
    
    $sql = "SELECT * FROM `table` LIMIT 0, 30;";
    $result = $db->query($sql);
    
    while($row = $result->fetch_assoc())
    {
    	echo $row['id'];
    }
    Code (markup):
    When dealing with the MySQLi extension, you may use it in an object-oriented manner, or the procederal manner.
     
    Trikun3, May 22, 2010 IP
  3. bartolay13

    bartolay13 Active Member

    Messages:
    735
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    98
    #3
    everything must be dynamic.. even your mysql functions. anyways you are thinking far ahead, dont make it too complicated.. this is simple switch condition.
     
    bartolay13, May 23, 2010 IP