首發於:http://www.zzzzy.com/201406053158.html
1 /** 2 * Mysql表字段一鍵生成創建sqlite的SQL 3 * $db 數據庫 4 * $tbname 表名 5 * $is_blob 需要保存的圖片二進制數組 array("img1","img2","img3")形式,默認為false 6 * $retbname 自定義生成sqlite的表名 7 * return SQL的語句形式 8 */ 9 10 public function creat_sqlite($db, $tbname, $is_blob = false, $retbname = false){ 11 12 $runsql1 = $db->query("SELECT * FROM `$tbname` limit 1"); 13 $fields_rows = $runsql1->columnCount(); 14 15 $tb_fields_info = array(); 16 $tb_string = ""; 17 $dot = ""; 18 19 for ($i = 0; $i < $fields_rows; $i++) { 20 if ($i == 1) { 21 $dot = ", "; 22 } 23 24 $tb_meta = $runsql1->getColumnMeta($i); 25 $tb_string .= $dot.$tb_meta['name']; 26 //var_dump($tb_meta); 27 28 //如果存在數據且字段存在需要取消的字段中 29 if ($is_blob && in_array($tb_meta['name'], $is_blob)) { 30 $tb_string .= " "."blob"; 31 } else { 32 //如果不需要保存為二進制 33 switch($tb_meta['native_type']){ 34 case "VAR_STRING": 35 $tb_string .= " "."varchar"; 36 break; 37 38 case "LONG": 39 $tb_string .= " "."integer"; 40 break; 41 42 case "BLOB": 43 $tb_string .= " "."text"; 44 break; 45 case "TINY": 46 $tb_string .= " "."smallint"; 47 break; 48 } 49 } 50 51 if (isset($tb_meta['flags'][1]) && ($tb_meta['flags'][1] === "primary_key")) { 52 $tb_string .= " "."PRIMARY KEY"; 53 } 54 55 if (isset($tb_meta['flags'][0]) && ($tb_meta['flags'][0] === "not_null")) { 56 $tb_string .= " "."NOT NULL"; 57 } 58 59 //var_dump($tb_meta); 60 } 61 62 //生成的sqlite表名 63 $retbname = $retbname == true ? $retbname : $tbname; 64 65 //創建數據的SQL語句 66 $creat_data = "CREATE TABLE IF NOT EXISTS {$retbname} ($tb_string);"; 67 68 return $creat_data; 69 }