PHP将数组存入数据库中的四种方式
PHP将数组存入数据库中的四种方式
最近突然遇到了一个问题,如何用PHP将数组存入到数据库中,经过自己的多方查找和研究,总结了以下四种方法:
1.implode()和explode()方式
2.print_r()和自定义函数方式
3.serialize()和unserialize()方式
4.json_encode()和json_decode()方式
[php] view plain copy
1.<?php
2. // 将数组存入数据库中的四种方式详见我的博客
3. //1.implode和explode方式
4. //2.print_r和自定义函数方式
5. //3.serialize和unserialize方式
6. //4.json_encode和json_decode方式
7. // 如果想运行该文件,需要建立数据库admin,和数据表test,或者修改代码
8. // //---------------------------------------------------------------
9. // CREATE TABLE `test` (
10. // `id` int(10) unsigned NOT NULL AUTO_INCREMENT key,
11. // `array` text,
12. // ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
13. //定义用print_r将数组存储到数据库中的类
14.
15.header('content-type:text/html; charset=utf8');
16. define("DB_HOST","localhost");
17. define("DB_USER","root");
18. define("DB_PWD","0227");
19. define("DB_DBNAME","admin");
20. define("DB_CHARSET","utf8");
21. // 定义逆置print_r值的类
22.class Trie {
23. protected $dict = array();
24. protected $buf = '';
25. function set($word, $value='') {
26. if(is_array($word)) foreach($word as $k=>$v) $this->set($k, $v);
27. $p =& $this->dict;
28. foreach(str_split($word) as $ch) {
29. if(! isset($p[$ch])) $p[$ch] = array();
30. $p =& $p[$ch];
31. }
32. $p['val'] = $value;
33. return $this;
34. }
35. function parse($str) {
36. $this->doc = $str;
37. $this->len = strlen($str);
38. $i = 0;
39. while($i < $this->len) {
40. $t = $this->find($this->dict, $i);
41. if($t) {
42. $i = $t;
43. $this->buf = '';
44. }else $this->buf .= $this->doc{$i++};
45. }
46. }
47. protected function find(&$p, $i) {
48. if($i >= $this->len) return $i;
49. $t = 0;
50. $n = $this->doc{$i};
51. if( isset($p[$n]) ) $t = $this->find($p[$n], $i+1);
52. if($t) return $t;
53. if( isset($p['val']) ) {
54. $ar = explode(',', $p['val']);
55. call_user_func_array( array($this, array_shift($ar)), $ar );
56. return $i;
57. }
58. return $t;
59. }
60. function __call($method, $param) {
61. echo "****\n$this->buf 未定义方法:$method 参数:" . join(',', $param) . "<br />\n";
62. }
63.}
64.
65.
66.
67.class App extends Trie {
68. public $res = array();
69. protected $stack = array();
70. protected $keyname = '';
71. protected $buf = '';
72. function __construct() {
73. $this->stack[] =& $this->res;
74. }
75. protected function group() {
76. if(! $this->keyname) return;
77. $cnt = count($this->stack) - 1;
78. $this->stack[$cnt][$this->keyname] = array();
79. $this->stack[] =& $this->stack[$cnt][$this->keyname];
80. $this->keyname = '';
81. }
82. protected function brackets($c) {
83. $cnt = count($this->stack) - 1;
84. switch($c) {
85. case ')':
86. if($this->keyname) $this->stack[$cnt][$this->keyname] = trim($this->buf);
87. $this->keyname = '';
88. array_pop($this->stack);
89. break;
90. case '[':
91. if($this->keyname) $this->stack[$cnt][$this->keyname] = trim($this->buf);
92. break;
93. case ']':
94. $this->keyname = $this->buf;
95. }
96. $this->buf = '';
97. }
98.}
99.//类结束
100.//
101.//
102.//连接数据库
103. function connect(){
104. $link = @mysql_connect(DB_HOST,DB_USER,DB_PWD) or die("数据库连接失败ERR:".mysql_errno().":".mysql_error());
105. mysql_select_db(DB_DBNAME) or die("打开数据库失败");//mysql_errno()即显示错误数量;mysql_error()即显示错误信息;
106. $sql = 'set names '.DB_CHARSET;
107. mysql_query($sql) or die ("设置字符集失败");
108. return $link;
109. }
110.//插入数据库函数
111.
112. function insert($table, $array){
113. $keys = join(",",array_keys($array));
114. $vals = "'".join("','",array_values($array))."'";
115. $sql = "insert {$table}({$keys})values({$vals})";
116.
117. mysql_query($sql);
118. return mysql_insert_id();
119. }
120. //提取刚刚插入的数据
121. function select($table){
122. $sql = "select array from {$table} order by id desc";
123. if($result = mysql_query($sql)){
124. $values = mysql_fetch_assoc($result);
125. $value = array_pop($values);
126. }else{
127. echo '提取失败';
128. }
129. return $value;
130. }
131.
132.//implode方式 一维数组可以,二维数组不可以,并且关联数组无效
133. function plode($table,$arr){
134. echo '<h3 style="color:red"><b>implode</b>方式<br/>原数组,未插入前:</h3>';
135. var_dump($arr);
136. $str = addslashes(implode(",", $arr));
137. $insert = array('id'=>'','array'=>$str);
138. if(insert($table,$insert)){
139. echo "插入成功.<br/>";
140. }else{
141. echo "插入失败";
142. exit;
143. }
144. $value = select($table);
145. echo '<h3 style="color:red"><插入的内容:></h3>';
146.
147. var_dump($value);
148. $explode = explode(",",$value);
149. echo '<h3 style="color:red"><最终提取后处理的内容:></h3>';
150. var_dump($explode);
151.
152. }
153.
154.// print_r方式
155. function printR($table,$arr){
156. echo '<h3 style="color:red"><b>print_r方式</b><br/>原数组,未插入前:></h3>';
157. var_dump($arr);
158.
159. $print = addslashes(print_r($arr, true));
160. $insert = array('id'=>'','array'=>$print);
161. insert($table,$insert);
162. $value = select($table);
163.
164.
165. echo '<h3 style="color:red"><插入的内容:></h3>';
166.
167. var_dump($value);
168.$p = new App;
169.$p->set('Array','group')
170. ->set('[','brackets,[')
171. ->set('] =>','brackets,]')
172. ->set(')','brackets,)');
173.$p->parse($value);
174. echo '<h3 style="color:red"><最终提取后处理的内容:></h3>';
175.
176.var_dump($p->res);
177. }
178.
179.
180.// serialize方式
181.function serial($table,$arr){
182. echo '<h3 style="color:red"><b>serialize</b>方式<br/>原数组,未插入前:</h3>';
183. var_dump($arr);
184.
185. $serialize = addslashes(serialize($arr));
186. $insert = array('id'=>'','array'=>$serialize);
187. insert($table,$insert);
188. $value = select($table);
189. echo '<h3 style="color:red"><方式插入数据库中的内容:></h3>';
190. var_dump($value);
191. $serialize = unserialize($value);
192. echo '<h3 style="color:red"><最终提取后处理的内容:></h3>';
193. var_dump($serialize);
194.}
195.//json方式
196.function json($table,$arr){
197. echo '<h3 style="color:red"><b>json_encode</b>方式<br/>原数组,未插入前:</h3>';
198. var_dump($arr);
199.
200. $enjson = addslashes(json_encode($arr));
201. $insert = array('id'=>'','array'=>$enjson);
202. insert($table,$insert);
203. $value = select($table);
204. echo '<h3 style="color:red"><方式插入数据库中的内容:></h3>';
205. var_dump($value);
206. $deunjson = json_decode($value,true);
207. echo '<h3 style="color:red"><最终提取后处理的内容:></h3>';
208. var_dump($deunjson);
209.}
210.// 执行函数
211. //函数end
212.
213.
214.?>
215.<form action="" method="get">
216.<select name="kind">
217. <option value="1">一维数组</option>
218. <option value="2">二维数组</option>
219.
220.</select>
221.<select name="id">
222. <option value="1">implode方式</option>
223. <option value="2">print_r方式</option>
224. <option value="3">serialize方式</option>
225. <option value="4">json_encode方式</option>
226.
227.</select>
228.<input type="submit" value="提交" name="submit">
229.</form>
230.<?php
231.
232.if(!empty($_GET['submit'])){
233. $kind = $_GET['kind'];
234. $id = $_GET['id'];
235.
236.
237.}else{
238. echo "请选择后按提交键";
239. exit;
240.
241.}
242. connect();
243.$ar1 =array('abcd'=>"sdfasdf",'bbb'=>'lxg','ccc'=>'bbbbbbbbb');//定义一个一维数组
244.$ar2 = array('a'=>$ar1,'b'=>$ar1); //二维数组
245.$table = "test";//使用的数据表
246. if($kind=='1'){
247. $arr = $ar1;
248.}else{
249. $arr = $ar2;
250.}
251.switch ($id) {
252. case '1':
253. # code...
254. plode($table, $arr);
255. break;
256. case '2':
257. printR($table,$arr);
258. break;
259. case '3':
260. serial($table,$arr);
261. break;
262. case '4':
263. json($table,$arr);
264. break;
265. default:
266. break;
267. }
268.
269.?>
1.implode方式结果:
一维数组:
二维数组:报错
2.print_r方式
一维数组:
二维数组:
3.serialize方式:
一维数组:
二维数组:
4.json方式
一维数组:
二维数组:
以上几种方法从插入数据库的数据大小来看json方式最好,该演示中没有使用中文,如果将数组改成中文你会发现json的强大之处,第一种方式无法将多维数组存入数据库中,第二种方式还要用自定义类,推荐使用第三种和第四种方式!