PHP将数组存入数据库中的四种方式

1.implode()和explode()方
2.print_r()和自定义函数方式
3.serialize()和unserialize()方式
4.json_encode()和json_decode()方式

<?php
// 将数组存入数据库中的四种方式详见我的博客 http://blog.csdn.net/the_victory
//1.implode和explode方式
//2.print_r和自定义函数方式
//3.serialize和unserialize方式
//4.json_encode和json_decode方式
// 如果想运行该文件,需要建立数据库admin,和数据表test,或者修改代码
//   //---------------------------------------------------------------
//  CREATE TABLE `test` (
//   `id` int(10) unsigned NOT NULL AUTO_INCREMENT key,
//   `array` text,
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
  //定义用print_r将数组存储到数据库中的类

header('content-type:text/html; charset=utf8');
define("DB_HOST","localhost");
define("DB_USER","root");
define("DB_PWD","0227");
define("DB_DBNAME","admin");
define("DB_CHARSET","utf8");
// 定义逆置print_r值的类
class Trie {
  protected $dict = array();
  protected $buf = '';
  function set($word, $value='') {
    if(is_array($word)) foreach($word as $k=>$v) $this->set($k, $v);
    $p =& $this->dict;
    foreach(str_split($word) as $ch) {
        if(! isset($p[$ch])) $p[$ch] = array();
        $p =& $p[$ch];
    }
    $p['val'] = $value;
    return $this;
  }
  function parse($str) {
    $this->doc = $str;
    $this->len = strlen($str);
    $i = 0;
    while($i < $this->len) {
        $t = $this->find($this->dict, $i);
        if($t) {
            $i = $t;
            $this->buf = '';
        }else $this->buf .= $this->doc{$i++};
    }
  }
  protected function find(&$p, $i) {
    if($i >= $this->len) return $i;
    $t = 0;
    $n = $this->doc{$i};
    if( isset($p[$n]) ) $t = $this->find($p[$n], $i+1);
    if($t) return $t;
    if( isset($p['val']) ) {
        $ar = explode(',', $p['val']);
        call_user_func_array( array($this, array_shift($ar)), $ar );
        return $i;
    }
    return $t;
  }
  function __call($method, $param) {
    echo "****\n$this->buf 未定义方法:$method 参数:" . join(',', $param) . "<br />\n";
  }
}

class App extends Trie {
  public $res = array();
  protected $stack = array();
  protected $keyname = '';
  protected $buf = '';
  function __construct() {
    $this->stack[] =& $this->res;
  }
  protected function group() {
    if(! $this->keyname) return;
    $cnt = count($this->stack) - 1;
    $this->stack[$cnt][$this->keyname] = array();
    $this->stack[] =& $this->stack[$cnt][$this->keyname];
    $this->keyname = '';
  }
  protected function brackets($c) {
    $cnt = count($this->stack) - 1;
    switch($c) {
        case ')':
            if($this->keyname) $this->stack[$cnt][$this->keyname] = trim($this->buf);
            $this->keyname = '';
            array_pop($this->stack);
            break;
        case '[':
            if($this->keyname) $this->stack[$cnt][$this->keyname] = trim($this->buf);
            break;
        case ']':
            $this->keyname = $this->buf;
    }
    $this->buf = '';
  }
}
//类结束
//
//
//连接数据库
function connect(){
    $link = @mysql_connect(DB_HOST,DB_USER,DB_PWD) or die("数据库连接失败ERR:".mysql_errno().":".mysql_error());
    mysql_select_db(DB_DBNAME) or die("打开数据库失败");//mysql_errno()即显示错误数量;mysql_error()即显示错误信息;
   $sql = 'set names '.DB_CHARSET;
    mysql_query($sql) or die ("设置字符集失败");
    return $link;
}
//插入数据库函数

function insert($table, $array){
$keys = join(",",array_keys($array));
$vals = "'".join("','",array_values($array))."'";
$sql = "insert {$table}({$keys})values({$vals})";

mysql_query($sql);
return mysql_insert_id();
}
 //提取刚刚插入的数据
  function select($table){
   $sql = "select array from {$table} order by id desc";
  if($result = mysql_query($sql)){
  $values = mysql_fetch_assoc($result);
  $value = array_pop($values);
 }else{
 echo '提取失败';
 }
 return $value;
 }

//implode方式 一维数组可以,二维数组不可以,并且关联数组无效
function plode($table,$arr){
echo '<h3 style="color:red"><b>implode</b>方式<br/>原数组,未插入前:</h3>';
var_dump($arr);
$str = addslashes(implode(",", $arr));
$insert = array('id'=>'','array'=>$str);
if(insert($table,$insert)){
echo "插入成功.<br/>";
}else{
echo "插入失败";
exit;
}
$value = select($table);
echo '<h3 style="color:red"><插入的内容:></h3>';

var_dump($value);
$explode = explode(",",$value);
echo '<h3 style="color:red"><最终提取后处理的内容:></h3>';
var_dump($explode);

}

// print_r方式
function printR($table,$arr){
echo '<h3 style="color:red"><b>print_r方式</b><br/>原数组,未插入前:></h3>';
var_dump($arr);

$print = addslashes(print_r($arr, true));
$insert = array('id'=>'','array'=>$print);
insert($table,$insert);
$value = select($table);

echo '<h3 style="color:red"><插入的内容:></h3>';

var_dump($value);
$p = new App;
$p->set('Array','group')
  ->set('[','brackets,[')
  ->set('] =>','brackets,]')
  ->set(')','brackets,)');
$p->parse($value);
echo '<h3 style="color:red"><最终提取后处理的内容:></h3>';

var_dump($p->res);
}

// serialize方式
function serial($table,$arr){
echo '<h3 style="color:red"><b>serialize</b>方式<br/>原数组,未插入前:</h3>';
var_dump($arr);

$serialize = addslashes(serialize($arr));
$insert = array('id'=>'','array'=>$serialize);
insert($table,$insert);
$value = select($table);
echo '<h3 style="color:red"><方式插入数据库中的内容:></h3>';
var_dump($value);
$serialize = unserialize($value);
echo '<h3 style="color:red"><最终提取后处理的内容:></h3>';
var_dump($serialize);
}
//json方式
function json($table,$arr){
echo '<h3 style="color:red"><b>json_encode</b>方式<br/>原数组,未插入前:</h3>';
var_dump($arr);

$enjson = addslashes(json_encode($arr));
$insert = array('id'=>'','array'=>$enjson);
insert($table,$insert);
$value = select($table);
echo '<h3 style="color:red"><方式插入数据库中的内容:></h3>';
var_dump($value);
$deunjson = json_decode($value,true);
echo '<h3 style="color:red"><最终提取后处理的内容:></h3>';
var_dump($deunjson);
}
// 执行函数
 //函数end

?>
<form action="" method="get">
<select name="kind">
<option value="1">一维数组</option>
<option value="2">二维数组</option>

</select>
<select name="id">
<option value="1">implode方式</option>
<option value="2">print_r方式</option>
<option value="3">serialize方式</option>
<option value="4">json_encode方式</option>

</select>
<input type="submit" value="提交" name="submit">
</form>
<?php

if(!empty($_GET['submit'])){
$kind = $_GET['kind'];
$id = $_GET['id'];

}else{
echo "请选择后按提交键";
exit;

}
 connect();
$ar1 =array('abcd'=>"sdfasdf",'bbb'=>'lxg','ccc'=>'bbbbbbbbb');//定义一个一维数组
$ar2 = array('a'=>$ar1,'b'=>$ar1);//二维数组
$table = "test";//使用的数据表
if($kind=='1'){
$arr = $ar1;
}else{
$arr = $ar2;
}
switch ($id) {
case '1':
# code...
plode($table, $arr);
break;
case '2':
printR($table,$arr);
break;
case '3':
serial($table,$arr);
break;
case '4':
json($table,$arr);
break;
default:
break;
}

?>
(0)

相关推荐