Hola a todos, hoy os voy a dejar una clase que podéis utilizar para vuestros proyectos.
En PHP, normalmente necesitamos conectarnos a una base de datos, normalmente MySQL.
En este caso os dejo como hacerlo con PDO.
Con esta clase podréis hacerlo de forma fácil.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
class PDODB { private $host; private $usuario; private $pass; private $db; private $connection; function __construct($host, $usuario, $pass, $db) { $this->host = $host; $this->usuario = $usuario; $this->pass = $pass; $this->db = $db; } function connect() { $opciones = array( PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", PDO::MYSQL_ATTR_FOUND_ROWS => true ); $this->connection = new PDO( 'mysql:host=' . $this->host . ';dbname=' . $this->db, $this->usuario, $this->pass, $opciones ); } function getData($sql) { $data = array(); $result = $this->connection->query($sql); $error = $this->connection->errorInfo(); if ($error[0] === "00000") { $result->execute(); if ($result->rowCount() > 0) { while ($row = $result->fetch(PDO::FETCH_ASSOC)) { array_push($data, $row); } } } else { throw new Exception($error[2]); } return $data; } function numRows($sql) { $result = $this->connection->query($sql); $error = $this->connection->errorInfo(); if ($error[0] === "00000") { $result->execute(); return $result->rowCount(); } else { throw new Exception($error[2]); } } function getDataSingle($sql) { $result = $this->connection->query($sql); $error = $this->connection->errorInfo(); if ($error[0] === "00000") { $result->execute(); if ($result->rowCount() > 0) { return $result->fetch(PDO::FETCH_ASSOC); } } else { throw new Exception($error[2]); } return null; } function getDataSingleProp($sql, $prop) { $result = $this->connection->query($sql); $error = $this->connection->errorInfo(); if ($error[0] === "00000") { $result->execute(); if ($result->rowCount() > 0) { $data = $result->fetch(PDO::FETCH_ASSOC); return $data[$prop]; } } else { throw new Exception($error[2]); } return null; } function executeInstruction($sql) { $result = $this->connection->query($sql); $error = $this->connection->errorInfo(); if ($error[0] === "00000") { $result->execute(); return $result->rowCount() > 0; } else { throw new Exception($error[2]); } } function close() { $this->connection = null; } function getLastId() { return $this->connection->lastInsertId(); } } |
Espero que os sea de ayuda. Si tenéis dudas, preguntad. Estamos para ayudarte.
Deja una respuesta