Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class DatabaseConnection {
- protected $db_user = '';
- protected $db_pass = '';
- protected $db_dsn = 'mysql:host=localhost;dbname=';
- protected $options = array(
- PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
- PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
- );
- public function dbconnect(){
- try {
- $db = new PDO($this->db_dsn, $this->db_user, $this->db_pass, $this->options);
- }
- catch (PDOException $e) {
- echo 'Connection failed: ' . $e->getMessage();
- exit;
- }
- return $db;
- }
- }
- class dbTools {
- private $db;
- private $verifiedTable;
- private $verifiedColumn;
- private $verifiedItemId;
- function __construct() {
- $this->db = new DatabaseConnection();
- $this->db = $this->db->dbconnect();
- }
- public function validateValues($table, $column, $itemId) {
- // Verify that table exists
- $verifiedTable = $this->verifyTable($table);
- $this->verifiedTable = $verifiedTable;
- // Verify that column exists
- $verifiedColumn = $this->verifyColumn($column, $this->verifiedTable);
- $this->verifiedColumn = $verifiedColumn;
- // Verify that id exists
- $verifiedItemId = $this->verifyItemId($this->verifiedTable, $itemId);
- $this->verifiedItemId = $verifiedItemId;
- }
- private function verifyTable($table) {
- $result = $this->db->query("show tables");
- $final = $result->fetchAll(PDO::FETCH_COLUMN);
- if(in_array($table, $final)) {
- $verifiedTable = $table;
- } else {
- throw new exception('Table doesn´t exists');
- }
- return $verifiedTable;
- }
- private function verifyColumn($column, $verifiedTable) {
- $result = $this->db->query('SHOW COLUMNS FROM '.$verifiedTable.'');
- $columns = $result->fetchAll(PDO::FETCH_COLUMN);
- if(in_array($column, $columns)) {
- $verifiedColumn = $column;
- } else {
- throw new exception('Column doesn´t exist');
- }
- return $verifiedColumn;
- }
- private function verifyItemId($verifiedTable, $itemId) {
- $result = $this->db->query('SELECT id FROM '.$verifiedTable.'');
- $ids = $result->fetchAll(PDO::FETCH_COLUMN);
- if(in_array($itemId, $ids)) {
- $verifiedItemId = $itemId;
- } else {
- throw new exception('Id doesn´t exist');
- }
- return $verifiedItemId;
- }
- public function getItem() {
- $statement = 'SELECT '.$this->verifiedColumn.' FROM '.$this->verifiedTable.' WHERE id = :id';
- $query = $this->db->prepare($statement);
- $query->bindParam(':id', $this->verifiedItemId);
- $query->execute();
- $row = $query->fetchColumn();
- return $row;
- }
- }
- $dbTools = new dbTools();
- $dbTools->validateValues('table','column', 'id');
- echo $dbTools->getItem();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement