Jump to content

оцените работу


viktorino
 Share

Recommended Posts

Доброго времени суток. до недавного времени я программировал CMS обычным способом PHP

сейчас начал осваивать OOP PHP  собвственно пишу  новую  CMS  на OOP PHP дабы в будущем можно было ее совершенствовать без проблем,а не как на обычном PHP программирование.

 

оцените мой первый написаный  метод который будет разговаривать с базой данных  с  1 таблицей включающий в себя все возможные виды запросов.

 

буду рад  вашим советам и отзывам. !!

 

вот собвственно он :

	 class DBWork { 	 	private $dbh;	 	private $config; 	private $valid; 	public function __construct(){ 		$this->config = new Config(); 		$this->valid = new CheckValid(); 		try {	 		$this->dbh = new PDO('mysql:host='.$this->config->host.';dbname='.$this->config->dbName.';charset=utf8',$this->config->userName,$this->config->password);			$this->dbh->setAttribute(PDO::ATTR_ERRMODE,  PDO::ERRMODE_EXCEPTION);					} 		catch (PDOException $e) {			//var_dump($e);			echo $e->getMessage();		} 	} 	/* ========= SELECT ALL AND ONE ITEM METHODS ARGUMENTS SETTINGS  =================	arg 1 = table name - required.	arg 2 = fields - required. for example : array("name","id") very important insert all fields inside array even if you have a single field or you selecting  all fields like this (*)	olso you can us mysql functions like count() or sum() or any thing alse like this: count(`id`) , sum(`id`).	arg 3 = for WHERE clause - optional for exampele : "`id` = " or "`name` = ".	arg 4 = for WHERE clause -  required if arg 3 was inserted  example of use : "`id` = ","3" or "`name` = ","viktor".	arg 5 = for AND clause - optional for example : "`custumer` = " or "`age` = ".	arg 6 = for AND clause -  required if arg 5 was inserted  example of use : "`custumer` = ","exists" or "`age` = ","28".	arg 7 = ORDER BY clause - optioal  for example : "`id`" or "`age`"  by default its by "`id`".	arg 8 = optional ORDER BY FIRST TO LAST $up = true AND BY LAST TO FIRST $up = false  . by default $up = true.	arg 9 = LIMIT optional for example "2" or "10". by default there is no limit.	EXAMPLE OF USE	using all arguments : select("`test`", array("id","name"), "`id` =", "3", "`name`=", "viktor", "`order`" ,$up=true, "2");	using only required arguments :  select("`test`", array("id","name"));	using order by and limit : select("`test`", array("id","name"), "", "", "", "", "`order`" ,$up=true, "2");	-= VERY IMPORTANT TO LEAVE THE PREVIOUS FIELDS EMPTY IF YOU WANT  TO MAKE A REQUEST  WITHOUT CLAUSES  WHERE and  AND =-		*/	/* === SELECT ALL METHOD === */ 	public function selectAll($table, $fields, $where = "", $whereVal="", $and="", $andVal="", $order = "", $up = true, $limit = ""){ 		for($i = 0; $i < count($fields); $i++){ 			if(strpos($fields[$i], "(") === false && $fields[$i] != "*"){ $fields[$i] = "`".$fields[$i]."`";} 		} 		$fields = implode(",",$fields); 		if(!$order){ 		 $order = " ORDER BY `id`"; 		}else{ 			if($order != " RAND() "){ 				$order = "ORDER BY $order "; 				if(!$up) $order .= " DESC "; 			}else{ 				$order = " ORDER BY $order "; 			} 		} 		if($limit) $limit = " LIMIT $limit "; 		if($where && !$and){ 	 			try { 				if($whereVal){ 				   $query = $this->dbh->prepare("SELECT $fields FROM $table WHERE $where:val $order $limit");			       $query->bindParam(":val",$whereVal,PDO::PARAM_STR); 				}else{ 					throw new Exception("Check WHERE clouse argument and argument value in SELECT METHOD All() that you call!!! It cant Be EMPTY!!!!"); 					 				}								} catch (Exception $ex) {									echo "<div style=\"border:2px dotted #ff0000;text-align:center;font-weight:bold;color:#ff0000;width:800px;margin:50px auto;\">Error: ".$ex->getMessage()."</div>";			}			}		if($and && $where){			try{				if($andVal && $whereVal){				$query = $this->dbh->prepare("SELECT $fields FROM $table WHERE $where:val AND $and:val2 $order $limit");				$query->bindParam(":val",$whereVal,PDO::PARAM_STR);				$query->bindParam(":val2",$andVal,PDO::PARAM_STR);				}else{ 					throw new Exception("Check if you calling to existing  AND & WHERE clouses arguments and arguments values in SELECT ALL() METHOD that you call!!! they cant Be EMPTY and must be existing!!!!"); 					 				}								} catch (Exception $ex) {									echo "<div style=\"border:2px dotted #ff0000;text-align:center;font-weight:bold;color:#ff0000;width:800px;margin:50px auto;\">Error: ".$ex->getMessage()."</div>";			}								 }		 if(!$where){ 			$query =  $this->dbh->prepare("SELECT $fields FROM $table $order $limit"); 			 		} 		try { 			if(isset($query)){	 		try {	 			 $query->execute(); 				 $rows = $query->fetchAll(PDO::FETCH_ASSOC);	 			 	 		} catch (PDOException $e) {	 			$arr = $e->errorInfo[2];	 			echo "<div style=\"border:2px dotted #ff0000;text-align:center;font-weight:bold;color:#ff0000;width:800px;margin:50px auto;\">".$arr."<br >Please Check your syntax in SELECT ALL() method that you call !!! </div> ";	 			//var_dump($e);	 				 		} 					 	}else{	 		throw new Exception("QUERY DO NOT EXISTS!!!");	 			 	} 			 		} catch (Exception $ex) { 			echo "<div style=\"border:2px dotted #ff0000;text-align:center;font-weight:bold;color:#ff0000;width:800px;margin:50px auto;\">Error: ".$ex->getMessage()."</div>"; 		} 		try { 			if (isset($rows) && $rows) { 			 return $rows;	         $this->dbh = null; 			}else{ 				throw new Exception("There is no returned Data from Data Base with method SELECT ALL()!!! Make sure that you calling a right fields with right Conditions !!!"); 			} 			 		} catch (Exception $ex) { 			echo "<div style=\"border:2px dotted #ff0000;text-align:center;font-weight:bold;color:#ff0000;width:800px;margin:50px auto;\">Error: ".$ex->getMessage()."</div>"; 		} 		 		 	}    }вызов метода  $CMSDBWORK = new  DBWork(); $s = $CMSDBWORK->selectAll("`test`",array("name","id"),"`id` <","4","`name` = ","","`order`");var_dump($s);
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy