Four ways in which PHP stores an array in a database

Source: Internet
Author: User
four ways in which PHP stores an array in a database recently encountered a problem, how to use PHP to store the array in the database, through their own multi-party search and research, summed up the following four methods: 1.implode () and explode () square
2.print_r () and Custom function methods
3.serialize () and Unserialize () method
4.json_encode () and Json_decode () method
<?php//Four ways to store an array in a database are described in my blog http://blog.csdn.net/the_victory//1.implode and explode//2.print_r and custom function//3. Serialize and Unserialize way//4.json_encode and Json_decode if you want to run the file, you need to set up Database admin, data table test, or modify code////--------------- ------------------------------------------------//CREATE TABLE ' Test ' (//' id ' int () unsigned not NULL auto_incr
  	Ement key,//' array ' text,//) Engine=innodb DEFAULT Charset=utf8;
	Defines the class header (' content-type:text/html; Charset=utf8 ') that stores the array in the database with Print_r;
	Define ("Db_host", "localhost");
	Define ("Db_user", "root");
	Define ("Db_pwd", "0227");
	Define ("Db_dbname", "admin");
	Define ("Db_charset", "UTF8");
  Classes class Trie {protected $dict = array () that defines the inverse print_r value.
  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; The function __call ($method, $param) {echo ****\n$this->buf undefined method: $method parameter: ". 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 = '; ///class End//////Connection Database function connect () {$link = @mysql_connect (db_host,db_user,db_pwd) or Die ("database connection Failed ERR:". Mysql_errno (). ":". Mysql_error ()); mysql_select_db (Db_dbname) or Die ("Open Database Failed"),//mysql_errno () displays the number of errors, mysql_error () displays error messages, $sql = ' Set names '.
	    Db_charset;
	    mysql_query ($sql) or Die ("Set charset failure");
	return $link;
		//Insert Database functions 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 ();
 	 //Extract just inserted data 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 ' extract failed ';
 return $value; //implode Way one-dimensional array can, two-dimensional array cannot, and associative array invalid function Plode ($table, $arr) {echo ' 

1.implode Mode Result:

One-dimensional arrays:

Two-dimensional array: Error

2.print_r Way

One-dimensional arrays:

Two-dimensional arrays:


3.serialize mode:

One-dimensional arrays:


Two-dimensional arrays:


4.json mode

One-dimensional arrays:


Two-dimensional arrays:


These methods are best viewed from the size of the data inserted into the database, the demo does not use Chinese, if you change the array to Chinese you will find the power of JSON, the first way you can not store multidimensional arrays in the database, the second way to use a custom class, recommended the use of the third and fourth way.

After all, I have limited ability, if we find more ways and the shortcomings of the article, I hope to point out, thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.