Last active
June 10, 2019 09:26
-
-
Save belocer/a9d3c8b940badfa0f2f777000ebe52bc to your computer and use it in GitHub Desktop.
PDO
This file contains 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 | |
// Подключение к БД | |
$pdo = new PDO("mysql:host=localhost: dbname=test", "root", ""); | |
// Готовим запрос | |
$sql = "SELECT * FROM tasks"; | |
$statement = $pdo->prepare($sql); // подготовить запрос | |
$result = $statement->execute(); // вернет true || false // Запускает подготовленный запрос на выполнение | |
$tasks = $statement->fetchAll(PDO::FETCH_ASSOC); //Возвращает массив, содержащий все строки результирующего набора | |
/* Либо вот такой готовый вариант для проекта */ | |
class Dbconnect | |
{ | |
public $isConn; | |
public $datab; | |
// Connect to db | |
public function __construct($username = "root", $pass = "", $host = "localhost", $dbname = "cj34342_shop", $options = []) | |
{ | |
$this->isConn = TRUE; | |
try { | |
$this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $pass, $options); | |
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); | |
//$this->datab->exec('SET CHARACTER SET utf8'); | |
} catch (PDOException $e) { | |
throw new Exception($e->getMessage()); | |
} | |
} | |
// Disconnect form db | |
public function Disconnect() | |
{ | |
$this->datab = NULL; | |
$this->isConn = FALSE; | |
} | |
// get row | |
public function getRow($query, $params = []) | |
{ | |
try { | |
$stmt = $this->datab->prepare($query); | |
$stmt->execute($params); | |
return $stmt->fetch(); | |
} catch (PDOException $e) { | |
throw new Exception($e->getMessage()); | |
} | |
} | |
// get rows | |
public function getRows($query, $params = []) | |
{ | |
try { | |
$stmt = $this->datab->prepare($query); | |
$stmt->execute($params); | |
return $stmt->fetchAll(); | |
} catch (PDOException $e) { | |
throw new Exception($e->getMessage()); | |
} | |
} | |
// insert row | |
public function insertRow($query, $params = []) | |
{ | |
try { | |
$stmt = $this->datab->prepare($query); | |
$stmt->execute($params); | |
return $this->datab->lastInsertId(); // возвращаю id последней записи в бд | |
//return TRUE; | |
} catch (PDOException $e) { | |
throw new Exception($e->getMessage()); | |
} | |
} | |
// update row | |
public function updateRow($query, $params = []) | |
{ | |
$this->insertRow($query, $params); | |
return $this->datab->lastInsertId(); // возвращаю id последней записи в бд | |
} | |
// delete row | |
public function deleteRow($query, $params = []) | |
{ | |
$this->insertRow($query, $params); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment