-
Notifications
You must be signed in to change notification settings - Fork 16
/
DbHelper.php
61 lines (50 loc) · 1.55 KB
/
DbHelper.php
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
<?php
/**
* Created by PhpStorm.
* User: tebazil
* Date: 16.08.15
* Time: 22:34
*/
namespace tebazil\dbseeder;
use PDO;
class DbHelper
{
/**
* @var \PDO
*/
private $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function insert($table, $columns)
{
$columnString = implode(', ',array_keys($columns));
$placeholderValues = [];
foreach($columns as $columnName => $value) {
$placeholderValues[':'.$columnName]=$value;
}
$placeholderString = implode(', ',array_keys($placeholderValues));
$sql = 'INSERT INTO '.$table.'('.$columnString.') VALUES ('.$placeholderString.')';
echo '>>> Executing "'.$sql.'" with params: '.$this->getParamsForEcho($placeholderValues).PHP_EOL;
$stmt = $this->pdo->prepare($sql);
if(!$stmt instanceof \PDOStatement) {
throw new \InvalidArgumentException(print_r($this->pdo->errorInfo()));
}
return $stmt->execute($placeholderValues);
}
public function truncateTable($table)
{
$sql = (strpos('sqlite',$this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME))!==false ? "DELETE FROM ":"TRUNCATE TABLE ") . $table;
echo 'Executing "'.$sql.'"'.PHP_EOL;
$this->pdo->exec($sql);
}
private function getParamsForEcho($params) {
$ret = '(';
$pairs = [];
foreach($params as $placeholder=>$value) {
$pairs[]=$placeholder.' => '.$value;
}
$ret.=implode(', ',$pairs).')';
return $ret;
}
}