Skip to content

Commit e05838f

Browse files
committed
update
1 parent 6499b78 commit e05838f

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

src/Orm.php

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?php
2+
3+
namespace MintyPHP;
4+
5+
class Orm
6+
{
7+
/**
8+
* @param array<string, ?string> $object
9+
*/
10+
public static function insert(string $tableName, array $object): int
11+
{
12+
if (count($object) == 0) {
13+
return 0;
14+
}
15+
$fields = [];
16+
$qmarks = [];
17+
$params = [];
18+
foreach ($object as $key => $value) {
19+
$fields[] = $key;
20+
$qmarks[] = '?';
21+
$params[] = $value;
22+
}
23+
$fields = implode('`,`', $fields);
24+
$qmarks = implode(',', $qmarks);
25+
$sql = "INSERT INTO `$tableName` (`$fields`) VALUES ($qmarks)";
26+
return DB::insert($sql, $params);
27+
}
28+
29+
/**
30+
* @param array<string, ?string> $object
31+
*/
32+
public static function update(string $tableName, array $object, string|int $id, string $idField = 'id'): int
33+
{
34+
if (isset($object[$idField])) {
35+
unset($object[$idField]);
36+
}
37+
if (count($object) == 0) {
38+
return 0;
39+
}
40+
$fields = [];
41+
$qmarks = [];
42+
$params = [];
43+
foreach ($object as $key => $value) {
44+
if (!in_array(gettype($value), ['integer', 'double', 'string', 'NULL'])) {
45+
throw new \InvalidArgumentException("Invalid value type for $key: " . gettype($value));
46+
}
47+
$fields[] = $key;
48+
$params[] = $value;
49+
}
50+
$fields = implode('` = ?, `', $fields);
51+
$qmarks = implode(',', $qmarks);
52+
$sql = "UPDATE `$tableName` SET `$fields` = ? WHERE `$idField` = ?";
53+
$params[] = $id;
54+
var_dump([$sql, $params]);
55+
return DB::update($sql, $params);
56+
}
57+
58+
/**
59+
* @return array<string, ?string> $object
60+
*/
61+
public static function select(string $tableName, string|int $id, string $idField = 'id'): array
62+
{
63+
$sql = "SELECT * FROM `$tableName` WHERE `$idField` = ?";
64+
return DB::selectOne($sql, [$id])[$tableName] ?? [];
65+
}
66+
}

0 commit comments

Comments
 (0)