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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
<?php header('X-UA-Compatible: IE=edge,chrome=1'); function execute_sql($sql) { $result = mysql_query($sql); if (!$result) { $error = mysql_errno() . ' - ' . mysql_error(); echo $error; throw new Exception($error); } return $result; }
function get_record($sql, $record_not_found_msg = 'Record not found.') { $record = array(); $result = execute_sql($sql); if ($row = mysql_fetch_assoc($result)) { $record = $row; mysql_free_result($result); } else { echo $record_not_found_msg; throw new Exception($record_not_found_msg); } return $record; }
function &get_records($sql) { $result = execute_sql($sql); $records = array(); while ($row = mysql_fetch_assoc($result)) $records[] = $row; mysql_free_result($result); return $records; }
function save($id, $table, array $save_values, &$action=NULL, array &$model=array()) { // get table columns $sql = "SELECT column_name FROM information_schema.columns WHERE table_schema = (SELECT DATABASE()) AND table_name = '$table'"; $tmp_records = get_records($sql); $columns = array(); foreach ($tmp_records as $tmp_record) $columns[] = '`' . $tmp_record['column_name'] . '`'; // build save sql $values = array(); foreach ($save_values as $key => $value) { $variable = $key; $column = '`' . $variable . '`'; $$variable = $value; $html_variable = 'html_' . $variable; $$html_variable = htmlspecialchars($$variable, ENT_QUOTES); $mysql_variable = 'mysql_' . $variable; $$mysql_variable = empty($$variable) && strlen($$variable) == 0 ? 'NULL' : ("'" . mysql_real_escape_string($$html_variable) . "'"); $model[$variable] = $$html_variable; if (in_array($column, $columns)) $values[$column] = $$mysql_variable; } if (empty($id)) { // create if (in_array('`create_on`', $columns)) $values['`create_on`'] = 'NOW()';
$sql = "INSERT INTO `$table` (" . implode(', ', array_keys($values)) . ") VALUES (" . implode(', ', array_values($values)) . ")";
$action = 'Created'; } else { // update $segments = array(); foreach ($values as $column => $value) $segments[] = "$column = $value"; $sql = "UPDATE `$table` SET " . implode(', ', $segments) . " WHERE id = $id";
$action = 'Updated'; } execute_sql($sql); if (empty($id)) $id = mysql_insert_id(); return $id; }
|