MySQL Database Interaction PHP Class
There are many ways out there to connect to a database, but there is only a few of them that are effective. This is the MySQL object that I use to connect to a database via PHP. You will find this class to be simple but very effective as it’s not overfilled, but it only contains what it’s needed in order to compile a successful application. I have used it multiple times in tasks that include from basic user managements to custom cloud application development. From connecting to a single database, to multiple databases.
Here is the code, please make sure to replace the values of the variables so that you can successfully connect to your database.
class db{//Object Variables Please Replace, you can also have them set on the constructor so that you can connect to multiple databases.private $status;private $host = ‘localhost’;private $database = ‘db_name’;private $username = ‘username’;private $password = ‘password’;public ξ$result;public ξ$results;function __construct(){//Connect To Database$this->status = mysql_connect($this->host,$this->username,$this->password) or die (‘Cannot Open Conection to ‘ .$this->host);//Select Databasemysql_select_db($this->database,$this->status);}function query($sql){//Get Results$this->result = ξmysql_query($sql);}function fetch($sql,$type){//Perform Query$this->query($sql);switch ($type){//Fetch as an Arraycase ‘array’:$this->results = mysql_fetch_array($this->result);break;//Fetch as an Asspciative Arraycase ‘assoc’:$this->results = mysql_fetch_assoc($this->result);break;//Fetch as an Objectcase ‘object’:$this->results = mysql_fetch_object($this->result);break;}//Return Resultsreturn $this->results;}function checkit($sql){//Check Table for Queryreturn mysql_num_rows(mysql_query($sql));}function __destruct(){//Free Query Resultmysql_free_result($this->result);//Close DB Connectionmysql_close($this->status);}}
Please let any comments, suggestions orξrecommendationsξon the area below.