Advertisement
Guest User

Untitled

a guest
Mar 15th, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.46 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Class MySQL
  5. */
  6. class MySQL{
  7.  
  8. /**
  9. * @var PDO Conexión a la base de datos
  10. */
  11.  
  12. private $pdo;
  13.  
  14. /**
  15. * @var string Host de la BD
  16. */
  17.  
  18. private $dbhost;
  19.  
  20. /**
  21. * @var string User de la BD
  22. */
  23.  
  24. private $dbuser;
  25.  
  26. /**
  27. * @var string Pass de la bd
  28. */
  29.  
  30. private $dbpass;
  31.  
  32. /**
  33. * @var string Nombre de la BD
  34. */
  35.  
  36. private $dbname;
  37.  
  38. /**
  39. * @var string Nombre de la tabla
  40. */
  41.  
  42. private $table;
  43.  
  44. /**
  45. * @var string Campo a ordenar
  46. */
  47.  
  48. private $orderby;
  49.  
  50. /**
  51. * @var int Límite de registros
  52. */
  53.  
  54. private $limit;
  55.  
  56. /**
  57. * @var string Objeto a castear los resultados
  58. */
  59. private $object;
  60.  
  61. /**
  62. * Inicia la conexión
  63. *
  64. * @param string $dbhost Host
  65. * @param string $dbuser Usuario
  66. * @param string $dbpass Contraseña
  67. * @param string $dbname BD
  68. */
  69. public function __construct($dbhost, $dbuser, $dbpass, $dbname){
  70. $this->dbhost = $dbhost;
  71. $this->dbuser = $dbuser;
  72. $this->dbpass = $dbpass;
  73. $this->dbname = $dbname;
  74. $this->object = NULL;
  75.  
  76. $pdo = new PDO("mysql:host=" . $this->dbhost . ";dbname=" . $this->dbname . ";charset=utf8", $this->dbuser, $this->dbpass);
  77. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  78. $this->pdo = $pdo;
  79. }
  80.  
  81. /**
  82. * Devuelve el nombre de la table
  83. *
  84. * @return mixed
  85. */
  86. public function getTable(){
  87. return $this->table;
  88. }
  89.  
  90. /**
  91. * Asigna el nombre de la tabla
  92. *
  93. * @param string $table Nombre de la tabla
  94. */
  95. public function setTable($table){
  96. $this->table = $table;
  97. }
  98.  
  99. /**
  100. * Asigna el campo a ordenar
  101. *
  102. * @param string $orderby Campo a ordenar
  103. */
  104. public function setOrderBy($orderby){
  105. $this->orderby = $orderby;
  106. }
  107.  
  108. /**
  109. * Asigna el límite de registros
  110. *
  111. * @param int $limit Límite de registros
  112. */
  113. public function setLimit($limit){
  114. $this->limit = $limit;
  115. }
  116.  
  117. /**
  118. * Asigna el objeto a castear los resultados
  119. *
  120. * @param string $class Objeto a castear
  121. */
  122. public function setObject($class){
  123. $this->object = $class;
  124. }
  125.  
  126. /**
  127. * Devuelve el objeto a castear
  128. *
  129. * @return string Objeto a castear
  130. */
  131. public function getObject(){
  132. return $this->object;
  133. }
  134.  
  135. /**
  136. * @return PDO Obtiene la conexión
  137. */
  138. public function getPDO(){
  139. return $this->pdo;
  140. }
  141.  
  142. /**
  143. * Crea el SQL de la condición a partir del array
  144. *
  145. * $a["field"] => Campo
  146. * $a["value"] => Valor
  147. * $a["logic"] => Operador lógico (AND, OR, ...)
  148. * $a["op"] => Operador de comparación (=, <>, <, >, ...)
  149. *
  150. * FORMATO: $a["logic"] $a["field"] $a["op"] $a["value"]
  151. *
  152. * @param array $conditions Condiciones
  153. * @return bool|string SQL de la condición
  154. */
  155. private function condition($conditions){
  156. if (is_array($conditions)) {
  157. $i = 0;
  158. $conditionString = "";
  159. foreach ($conditions as $condition) {
  160. $k = $i++;
  161.  
  162. switch ($k) {
  163. case 0:
  164. $conditionString .= $condition["field"] . " " . $condition["op"] . " :" . $condition["field"];
  165. break;
  166.  
  167. default:
  168. $conditionString .= " " . $condition["logic"] . " " . $condition["field"] . " " . $condition["op"] . " :" . $condition["field"];
  169. break;
  170. }
  171. }
  172. return $conditionString;
  173. } else {
  174. return false;
  175. }
  176. }
  177.  
  178. /**
  179. * Otra información como el límite o el campo a ordenar
  180. *
  181. * @return string
  182. */
  183. private function others(){
  184. $others = "";
  185. if (isset($this->orderby)) {
  186. $others .= " ORDER BY " . $this->orderby;
  187. }
  188. if (isset($this->limit)) {
  189. $others .= " LIMIT " . $this->limit;
  190. }
  191. return $others;
  192. }
  193.  
  194. /**
  195. * Devuelve los resultados con las condiciones $data si procede
  196. *
  197. * @param array $data Condiciones
  198. * @return array|bool
  199. */
  200. public function select($data = NULL){
  201.  
  202. $condition = ($data != NULL) ? " WHERE " . $this->condition($data) : "";
  203. $condition .= $this->others();
  204.  
  205. $query = $this->pdo->prepare("SELECT * FROM " . $this->table . $condition);
  206.  
  207. if ($data != NULL) foreach ($data as $element) $query->bindValue(":" . $element["field"], $element["value"]);
  208.  
  209. if ($this->object != NULL) $query->setFetchMode(PDO::FETCH_CLASS, $this->object);
  210. else $query->setFetchMode(PDO::FETCH_ASSOC);
  211. try{
  212. $query->execute();
  213. $array = array();
  214.  
  215. while ($object = $query->fetch()) {
  216. $array[] = $object;
  217. }
  218. $return = $array;
  219.  
  220. }catch(PDOException $e){
  221. $return = false;
  222. }
  223.  
  224. return $return;
  225. }
  226.  
  227. /**
  228. * Devuelve EL resultado con las condiciones $data si procede
  229. *
  230. * @param array $data Condiciones
  231. * @return bool|mixed
  232. */
  233. public function single($data = NULL){
  234.  
  235. $condition = ($data != NULL) ? " WHERE " . $this->condition($data) : "";
  236. $condition .= $this->others();
  237.  
  238. $query = $this->pdo->prepare("SELECT * FROM " . $this->table . $condition . " LIMIT 1");
  239.  
  240. if ($this->object != NULL) $query->setFetchMode(PDO::FETCH_CLASS, $this->object);
  241. else $query->setFetchMode(PDO::FETCH_ASSOC);
  242.  
  243. if ($data != NULL) foreach ($data as $element) $query->bindValue(":" . $element["field"], $element["value"]);
  244.  
  245. try{
  246. $query->execute();
  247. $return = $query->fetch();
  248. }catch(PDOException $e){
  249. $return = false;
  250. }
  251.  
  252. return $return;
  253.  
  254. }
  255.  
  256. /**
  257. * Inserta un registro en la tabla
  258. *
  259. * @param array $data Campos del registro
  260. * @return bool
  261. */
  262. public function insert($data){
  263. $success = true;
  264. if ($data != NULL) {
  265.  
  266. $append = "";
  267. $prepend = "";
  268. $args = (count($data) - 1);
  269. $i = 0;
  270.  
  271. foreach ($data as $field => $value) {
  272. $k = $i++;
  273. switch ($k) {
  274. case 0:
  275. $append .= "(" . $field;
  276. $prepend .= "(:" . $field . "";
  277. break;
  278.  
  279. case $args:
  280. $append .= "," . $field . ")";
  281. $prepend .= ",:" . $field . ")";
  282. break;
  283.  
  284. default:
  285. $append .= "," . $field;
  286. $prepend .= ",:" . $field . "";
  287. break;
  288. }
  289. }
  290.  
  291. $sql = "INSERT INTO " . $this->table . " " . $append . " VALUES " . $prepend;
  292. $query = $this->pdo->prepare($sql);
  293.  
  294. foreach ($data as $field => $value) $query->bindValue(":" . $field, $value);
  295.  
  296. try{
  297. $query->execute();
  298. }catch(PDOException $e){
  299. $success = false;
  300. print $e->getMessage();
  301. }
  302. } else {
  303. $success = false;
  304. }
  305. return $success;
  306. }
  307.  
  308. /**
  309. * Elimina un registro de la tabla
  310. *
  311. * @param array $data Condiciones
  312. * @return bool
  313. */
  314. public function delete($data){
  315. $success = true;
  316. if ($data != NULL) {
  317. $sql = "DELETE FROM " . $this->table . " WHERE " . $this->condition($data);
  318. $query = $this->pdo->prepare($sql);
  319. if($data != NULL) foreach($data as $element) $query->bindValue(":".$element["field"],$element["value"]);
  320. try{
  321. $query->execute();
  322. }catch(PDOException $e){
  323. $success = false;
  324. }
  325. } else {
  326. $success = false;
  327. }
  328.  
  329. return $success;
  330. }
  331.  
  332. /**
  333. * Actualiza un registro de la tabla
  334. *
  335. * @param array $data Datos a actualizar
  336. * @param array $cond Condiciones
  337. * @return bool
  338. */
  339. public function update($data, $cond){
  340. $success = true;
  341. if ($data != NULL and $cond != NULL) {
  342. if ($data != NULL) {
  343. $append = '';
  344. $i = 0;
  345. foreach ($data as $field => $value) {
  346. $k = $i++;
  347. switch ($k) {
  348. case 0:
  349. $append .= $field . " = :data_" . $field;
  350. break;
  351.  
  352. default:
  353. $append .= " , ". $field . " = :data_" . $field;
  354. break;
  355. }
  356. }
  357. }
  358. if ($cond != NULL) $condition = $this->condition($cond);
  359.  
  360. $sql = "UPDATE " . $this->table . " SET " . $append . " WHERE " . $condition;
  361. $query = $this->pdo->prepare($sql);
  362.  
  363. if($data != NULL) foreach($data as $field => $value) $query->bindValue(":data_".$field,$value);
  364. if($cond != NULL) foreach($cond as $element) $query->bindValue(":".$element["field"],$element["value"]);
  365.  
  366. try{
  367. $query->execute();
  368. }catch(PDOException $e){
  369. $success = false;
  370. }
  371.  
  372. } else {
  373. $success = false;
  374. }
  375. return $success;
  376. }
  377.  
  378.  
  379. /**
  380. * Hace una consulta a modo manual
  381. *
  382. * @param string $query SQL de la consulta
  383. * @param array $data Datos
  384. * @return array|bool
  385. */
  386. public function manualSelect($query,$data){
  387.  
  388. $query = $this->pdo->prepare($query);
  389.  
  390. if ($data != NULL) foreach ($data as $field=>$value) $query->bindValue(":" . $field, $value);
  391.  
  392. if ($this->object != NULL) $query->setFetchMode(PDO::FETCH_CLASS, $this->object);
  393. else $query->setFetchMode(PDO::FETCH_ASSOC);
  394.  
  395.  
  396. try{
  397. $query->execute();
  398. $array = array();
  399.  
  400. while ($object = $query->fetch()) {
  401. $array[] = $object;
  402. }
  403. $return = $array;
  404. }catch(PDOException $e){
  405. $return = false;
  406. }
  407.  
  408. return $return;
  409. }
  410.  
  411. /**
  412. * Ejecuta una query SQL de forma manual
  413. *
  414. * @param string $query SQL del query
  415. * @param array $data Datos del query
  416. * @return bool
  417. */
  418. public function manualQuery($query,$data){
  419.  
  420. $query = $this->pdo->prepare($query);
  421.  
  422. if ($data != NULL) foreach ($data as $field=>$value) $query->bindValue(":" . $field, $value);
  423. $return = true;
  424.  
  425. try{
  426. $query->execute();
  427. }catch(PDOException $e){
  428. $return = false;
  429. }
  430.  
  431. return $return;
  432. }
  433.  
  434. /**
  435. * Comprueba si existe un registro dada una condicion
  436. *
  437. * @param array $data Condiciones
  438. * @return bool
  439. */
  440. public function check($data){
  441. $return = true;
  442. if ($data != NULL) {
  443. $condition = $this->condition($data);
  444. $sql = "SELECT COUNT(*) AS numRows FROM " . $this->table . " WHERE " . $condition;
  445. $query = $this->pdo->prepare($sql);
  446. foreach($data as $element) $query->bindValue(":".$element["field"],$element["value"]);
  447. $query->setFetchMode(PDO::FETCH_ASSOC);
  448. try{
  449. $query->execute();
  450. $data = $query->fetch();
  451. $return = ((int)$data["numRows"] > 0);
  452. }catch(PDOException $e){
  453. $return = false;
  454. }
  455. } else {
  456. $return = false;
  457. }
  458. return $return;
  459. }
  460.  
  461. /**
  462. * Devuelve el numero de registros dada una condicion
  463. * @param array $data Condiciones
  464. * @return bool|int
  465. */
  466. public function rows($data = NULL){
  467. if ($data != NULL) {
  468. $condition = $this->condition($data);
  469. $sql = "SELECT COUNT(*) AS numRows FROM " . $this->table . " WHERE " . $condition;
  470. $query = $this->pdo->prepare($sql);
  471. foreach($data as $element) $query->bindValue(":".$element["field"],$element["value"]);
  472. $query->setFetchMode(PDO::FETCH_ASSOC);
  473. try{
  474. $query->execute();
  475. $data = $query->fetch();
  476. $return = (int) $data["numRows"];
  477. }catch(PDOException $e){
  478. $return = false;
  479. }
  480. } else {
  481. $return = 0;
  482. }
  483. return $return;
  484. }
  485. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement