Go Back   CodingForums.com > :: Server side development > PHP > Post a PHP snippet

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-24-2011, 08:55 PM   PM User | #1
Mac II
New to the CF scene

 
Join Date: Feb 2011
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Mac II is an unknown quantity at this point
PHP MySQL class

Hello today i will show you a simple PHP MySQL class and post your comment for this class .

PHP Code:
<?php
class ConnectMySQL {
    Var 
$dbhost;
    Var 
$dbuser;
    Var 
$dbpass;
    Var 
$dbname;
    Var 
$connect;
    Var 
$selectdb;
    function 
__Construct($dbhost$dbuser$dbpass$dbname) {
        if(isset(
$dbhost) and isset($dbuser) and isset($dbpass) and isset($dbname)):
            
$this->connect mysql_connect($dbhost$dbuser$dbpass);
            
$this->selectdb mysql_select_db($dbname);
            return 
$this->connect;
            return 
$this->selectdb;
        else:
            Exit;
        Endif;
    }
}
$connect = new ConnectMySQL("localhost""root""pass""db");
?>
Thanks!
Mac II is offline   Reply With Quote
Old 02-24-2011, 10:13 PM   PM User | #2
Inigoesdr
Super Moderator


 
Inigoesdr's Avatar
 
Join Date: Mar 2007
Location: Florida, USA
Posts: 3,601
Thanks: 2
Thanked 397 Times in 390 Posts
Inigoesdr is a jewel in the roughInigoesdr is a jewel in the roughInigoesdr is a jewel in the rough
  • You shouldn't use "var" to declare your variables because it's ambiguous and the functionality could change -- use public/private/protected/static
  • Most of your variables don't need to be declared at the class level if you are only using them in the one function
  • Your constructor should be named "__construct" -- lowercase. It works uppercase, but the proper notation is lower. Same goes for your exit/endif keywords. You write VB, don't you?
  • Why do you have a class with a single method? You should add methods to do more(query, num rows, etc.) or just make it a function(assuming it's something that needs to be repeated).
Inigoesdr is offline   Reply With Quote
Old 02-25-2011, 05:04 PM   PM User | #3
Mac II
New to the CF scene

 
Join Date: Feb 2011
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Mac II is an unknown quantity at this point
1. I tried with private / public but returning this error : Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /homepages/26/d94605010/htdocs/lz/writecodeonline.com/php/index.php(98) : eval()'d code on line 2

I dont know why...

2 and 4. Yeh , this is just a simple mysql class , i am going to make advanced one soon
3.I like coding uppercase but sometimes i dont.
Mac II is offline   Reply With Quote
Old 02-25-2011, 05:19 PM   PM User | #4
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,635
Thanks: 4
Thanked 2,448 Times in 2,417 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Scope would replace the var completely. If your constructor is working, you are on a PHP5.x environment, so members should be declared as private $dbhost; for example. Don't use public in PHP for non-final members ever. Since its datatype weak its more work to hack together a __set than it is to provide accessors and mutators for each member.

Constructors do not return results, they return a reference to the created object (which I believe is actually copied from the new to the variable, and void is actually returned from the __construct). You cannot return $this->connect or $this->selectdb, and in a standard method/function you can only return one.

I wouldn't have any of these as members at all. That exposes a privacy problem, since var_dump and print_r can both see private members, this poses a security risk on systems that allow external developers to build on. Just passing the parameters is fine, all you need to track is a $connection variable.

Edit:
Also, I should mention that you are better off not exiting / dying from a method at all. You would be better throwing an exception and letting the calling scope determine what do to with it.
__________________
As of PHP 5.5, the MySQL library has been officially deprecated. It is recommended to move to either MySQLi or PDO libraries for your mysql connectivity. See here for help choosing which interface you prefer: http://php.net/manual/en/mysqlinfo.api.choosing.php
Fou-Lu is offline   Reply With Quote
Old 02-25-2011, 10:11 PM   PM User | #5
Mac II
New to the CF scene

 
Join Date: Feb 2011
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Mac II is an unknown quantity at this point
New code :
PHP Code:
class MySQL {
    public 
$array = array();
    function 
__construct($array[1], $array[2], $array[3], $array[4]) {
        if(isset(
$array[1]) and isset($array[2]) and isset($aray[3]) and isset($array[4])):
            
mysql_connect($array[1], $array[2], $array[3]);
            
mysql_select_db($array[4]);
            if(
mysql_error()):
                echo 
mysql_error();
            endif;
        else:
            throw new 
exception('Required fields not set.');
        endif;
    }function 
makeQuery($string) {
        return 
mysql_query($string);
    }
    function 
num_rows($string) {
        return 
mysql_num_rows($string);
    }
    function 
fetch_array($query) {
        return 
mysql_fetch_array($query);
    }
}
$mysql = new MySQL("host""root""pass""db");
$ff $mysql->makeQuery("SELECT * FROM table");
echo 
$mysql->num_rows($ff);
$row $mysql->fetch_array($ff);
echo 
$row['first']; 
I haven't tested it , if you find errors post it.
Mac II is offline   Reply With Quote
Old 02-25-2011, 11:29 PM   PM User | #6
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,635
Thanks: 4
Thanked 2,448 Times in 2,417 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
No, this won't work either. You cannot specify array access parameters in a function or method, that just doesn't make any sense.
Isset checks are pointless. You have not provide a means to escape from providing data to a function (empty is technically fine, the only thing you need to establish a database connection is the host). I'd use AND very sparingly as well. AND has a lower priority than || (but not OR) which both AND and OR have a lower priority than assignment. Use && and || unless you are intending to use the lower priority of the AND or OR.
This entire class is easily written as simply:
PHP Code:
<?php

class MySQLConnection // Don't leave it under just MySQL
{
    private 
$rConn;
    public function 
__construct($host$user ''$pass ''$dbname '')
    {
        @
mysql_connect($host$user$pass) or throw new Exception(mysql_error());
        if (!empty(
$dbname))
        {
            
$this->selectdb($dbname);
        }
    }

    public function 
selectdb($dbname)
    {
        @
mysql_select_db($dbname$this->rConn) or throw new Exception(mysql_error());
    }

    
// Whatever else.
}
MySQL itself is getting old. You are better off moving to either a PDO or MySQLi environment instead, both of which are object oriented by default.

Edit:
Lame, you can't throw from an or.
This will work as intended.
PHP Code:
<?php

class MySQLConnection // Don't leave it under just MySQL
{
    private 
$rConn;
    public function 
__construct($host$user ''$pass ''$dbname '')
    {
        if (!@
mysql_connect($host$user$pass))
        {
            throw new 
Exception(mysql_error());
        }
        if (!empty(
$dbname))
        {
            
$this->selectdb($dbname);
        }
    }

    public function 
selectdb($dbname)
    {
        if (!@
mysql_select_db($dbname$this->rConn))
        {
            throw new 
Exception(mysql_error());
        }
    }

    
// Whatever else.
}
?>
__________________
As of PHP 5.5, the MySQL library has been officially deprecated. It is recommended to move to either MySQLi or PDO libraries for your mysql connectivity. See here for help choosing which interface you prefer: http://php.net/manual/en/mysqlinfo.api.choosing.php

Last edited by Fou-Lu; 02-25-2011 at 11:33 PM..
Fou-Lu is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

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 On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 10:26 PM.


Advertisement
Log in to turn off these ads.