Last active
March 12, 2021 19:05
-
-
Save edsonmsantos/a4b748df50c777bf4d79429d9fc80076 to your computer and use it in GitHub Desktop.
Simple class for connection in MySQL database using PDO library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace database; | |
use PDO; | |
class connection { | |
private $database; | |
public function __construct() { | |
$host = 'localhost'; | |
$database = 'telegram'; | |
$username = 'root'; | |
$password = 'root'; | |
$dsn = 'mysql:host='.$host.';dbname=' . $database; | |
$user = $username; | |
$pass = $password; | |
try { | |
$this->database = new PDO($dsn, $user, $pass); | |
} catch (\Throwable $th) { | |
throw $th; | |
} | |
} | |
/** | |
* @return PDO | |
*/ | |
public function getDatabase(): PDO | |
{ | |
return $this->database; | |
} | |
/** | |
* @param string $sql | |
* @param array $parameters | |
* @return array | |
*/ | |
public function runQuery(string $sql, array $parameters = []): array | |
{ | |
$statement = $this->database->prepare($sql); | |
$statement->execute($parameters); | |
return $statement->fetchAll(PDO::FETCH_ASSOC); | |
} | |
/** | |
* @param string $tableName | |
* @param array $fields | |
* @param array $where | |
* @return array | |
*/ | |
public function select(string $tableName, array $fields = [], array $where = []): array | |
{ | |
if (count($fields) === 0) { | |
$sql = "select * from {$tableName}"; | |
} else { | |
$fields = implode(', ', $fields); | |
$sql = "select {$fields} from {$tableName}"; | |
} | |
if (count($where) > 0) { | |
if (count($where) === 2) { | |
$sql .= " where " . $where[0] . " = " . $where[1]; | |
} else { | |
$sql .= " where " . $where[0] . $where[1] . '"'. $where[2] .'"'; | |
} | |
} | |
return $this->runQuery($sql, []); | |
} | |
/** | |
* @param string $table | |
* @param array $fieldsAndValues | |
* @return array | |
*/ | |
public function create(string $table, array $fieldsAndValues = []): array | |
{ | |
$keys = ""; | |
$values = ""; | |
foreach ($fieldsAndValues as $key => $value) { | |
$keys .= $key . ", "; | |
} | |
foreach ($fieldsAndValues as $key => $value) { | |
$values .= '"' . $value . '", '; | |
} | |
$keys = substr($keys, 0, -2); | |
$values = substr($values, 0, -2); | |
$sql = "insert into {$table} ($keys) values ($values)"; | |
return $this->runQuery($sql); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment