Newer
Older
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
class DatabaseTable
{
public $fields = array();
public $field_meta = array();
public $primary_key = NULL;
private $database;
private $table_name;
public function __construct( $database, $table_name )
{
$this->database = $database;
$this->table_name = $table_name;
}
/**
* Will attempt to bind columns with datatypes based on parts of the column type name
* Any part of the name below will be picked up and converted unless otherwise sepcified
* Example: 'VARCHAR' columns have 'CHAR' in them, so 'char' => PDO::PARAM_STR will convert
* all columns of that type to be bound as PDO::PARAM_STR
* If there is no specification for a column type, column will be bound as PDO::PARAM_STR
*/
protected $pdo_bind_types = array(
'char' => PDO::PARAM_STR,
'int' => PDO::PARAM_INT,
'bool' => PDO::PARAM_BOOL,
'date' => PDO::PARAM_STR,
'time' => PDO::PARAM_INT,
'text' => PDO::PARAM_STR,
'blob' => PDO::PARAM_LOB,
'binary' => PDO::PARAM_LOB
);
/**
* Parse PDO-produced column type
* [internal function]
*/
protected function parseColumnType($col_type)
{
$col_info = array();
$col_parts = explode(" ", $col_type);
if( $fparen = strpos($colParts[0], "(") )
{
$col_info['type'] = substr($col_parts[0], 0, $fparen);
$col_info['pdo_type'] = '';
$col_info['length'] = str_replace(")", "", substr($col_parts[0], $fparen+1));
$col_info['attributes'] = isset($col_parts[1]) ? $col_parts[1] : NULL;
}
else
{
$col_info['type'] = $col_parts[0];
}
// PDO Bind types
$pdo_type = '';
foreach($this->pdo_bind_types as $pKey => $pType)
{
if(strpos(' '.strtolower($col_info['type']).' ', $pKey))
{
$col_info['pdo_type'] = $pType;
break;
}
else
{
$col_info['pdo_type'] = PDO::PARAM_STR;
}
}
return $col_info;
}
/**
* Automatically get column metadata
*/
protected function getColumnMeta($refresh = false)
{
if( $refresh )
{
// Clear any previous column/field info
$this->fields = array();
$this->field_meta = array();
$this->primary_key = NULL;
}
// Automatically retrieve column information if column info not specified
if( count($this->fields) == 0 || count($this->field_meta) == 0 )
{
// Fetch all columns and store in $this->fields
// TODO prepared statement ...
$columns = $this->database->query("SHOW COLUMNS FROM " . $this->table_name, PDO::FETCH_ASSOC);
foreach( $columns as $key => $col )
{
// Insert into fields array
$col_name = $col['Field'];
$this->fields[$col_name] = $col;
if( $col['Key'] == "PRI" && empty($this->primary_key) )
{
$this->primary_key = $col_name;
}
// Set field types
$col_type = $this->parseColumnType($col['Type']);
$this->field_meta[$col_name] = $col_type;
}
}
return true;
}
}