一、使用Smarty模板
1、測試安裝
$tpl->testInstall();
Smarty Installation test...
Testing template directory...
/mnt/hgfs/study.com/smarty/templates is OK.
Testing compile directory...
/mnt/hgfs/study.com/smarty/templates_c is OK.
Testing plugins directory...
/mnt/hgfs/study.com/smarty/libs/plugins is OK.
Testing cache directory...
/mnt/hgfs/study.com/smarty/cache is OK.
Testing configs directory...
/mnt/hgfs/study.com/smarty/configs is OK.
Testing sysplugin files...
... OK
Testing plugin files...
... OK
Tests complete.
2、初始配置
注意:定界符 和css衝突
$smarty->template_dir = 'templates'; //配置模板所在目錄
$smarty->compile_dir = 'templates_c'; // 編譯後文件存儲目錄
$smarty->config_dir = 'configs'; // 配置文件目錄
$smarty->cache_dir = 'cache'; //緩存目錄
$smarty->left_delimiter='<{';
$smarty->right_delimiter='}>';
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;
$smarty->assign('title','第一次學習Smarty,好緊張啊...'); //看下面test.tpl中內容
$smarty->assign('color','red'); //看下面test.tpl中內容
$smarty->assign('content','測試成功沒有!');
二、Smarty的表現邏輯
1、註釋
html註釋在頁面源碼中可見,而smarty註釋則不能
{config_load file="test.conf" section="setup"}
{include file="header.tpl" title=foo}
<PRE>
{* 從配置文件讀取粗體和標題 *}
{if #bold#}<b>{/if}
2、聲明變量
通過assign在模板中聲明變量
直接通過$變量名稱=值,聲明變量並且賦值
{assign var=num value=1000}
{$num}
{$name = 'hello'}
{$name}
==注意:變量命名要符合變量命名規則==
3、常用變量修飾符
capitalize [首字母大寫]
count_characters [計算字符數]
cat [連接字符串]
count_paragraphs [計算段落數]
count_sentences [計算句數]
count_words [計算詞數]
date_format [時間格式]
default [默認]
escape [轉碼]
indent[縮進]
lower[小寫 ]
nl2br[換行符替換成<br />]
regex_replace[正則替換]
replace[替換]PHP面向對象面試題一
PHP面試題
1、寫出php的三種訪問控制模式的區別
答:public:表示公共的,在本類中和子類中以及類外,可以對其調用;
private:私有的,不能調用只能在它的本身中調用;
protected:表示受保護的,可以在本類中和子類中調用
2、藉助繼承,我們可以創建其他類的派類。在PHP中。子類最多可以繼承幾個父類
答:一個;
3、根據需求寫代碼
1.定義一個類:A:其中有一個成員屬性name
2.定義一個類:B:繼承A
3.實例化A的類不能直接訪問或修改name值
4.在B類中定義一個print_var方法,該方法返回A類的name值
5.實例化B,並調用print_var,寫出返回值
<?php
class A{
protected $name = 'zhangsan';
}
class B extends A{
public function print_var(){
return $this -> name;
}
}
$a = new A();
$b = new B();
echo $b -> print_var();
?>
5、請寫出至少7個PHP中魔術方法並說明各自的用戶法
答:__construct(構造函數):構造方法是實例化對象的時候自動執行的方法,作用就是初始化對象。該方法可以沒有參數,也可有多個參數,那麼在實例化這個對象的時候就要填上相對應的參數,
__toString():當程序使用echo和print輸出時對象,會自動調用該方法目的是希望無參數,但是該方法必須有返回值
__autoload():當程序執行到實例化的某個類的時候。如果在實例化前沒有引用這個類就會執行__autoload()這個函數
__destruct(析構函數):析構方法作用和構造方法正好相反,是對象被銷燬時被調用的作用是釋放內存,析構方法沒有參數
__call():當程序調用一個不存在或不可見的成員屬性時會自動執行__call(),它有兩個參數,分別是未訪問到的方法名稱和方法的參數,而第二個參數是數組類型
__set():當程序試圖寫入一個未定義的或不可見的成員屬性時,PHP就會自動執行__set().它包含了兩個參數,分別表示屬性名和屬性值
__get():當程序調用一個未定義的或不可見的成員屬性是,會自動觸發執行__get()它有一個參數,表示要調用的屬性名稱
__clone():當程序clone一個對象的時候,能觸發__clone()方法
6、請以代碼的形式體現以下問題
1.如何聲明一個名爲''myclass''的沒有方法和屬性的類?
2.如何實例化一個名爲''myclass''的對象
3.如何給私有的屬性賦值 至少寫出2中方法體現
class myclass
{
public function __set($name,$value){
$this->$name = $value;
}
public function func($value){
$this->temp = $value;
}
public function ss(){
echo $this->temp;
}
}
$kun = new myclass();
$kun -> temp = 154212;
$kun -> ss();
7、類的屬性可以序列化後保存到session中,從而可以恢復整個類,這要用到的函數是
答:session_start()/開啓會話
serialize() /序列化
unserialize()/反序列化
8、根據需求寫代碼
1.定義一個類:A,A中有一個disName的方法,方法中輸出''AAA''
2.定義一個類:B,B中有一個disName的方法,方法中輸出''BBB''
3.B類繼承A
4.實例化B,並調用對象disName方法
5.寫出輸出
<?php
class A{
public function disName(){
echo 'AAA';
}
}
class B extends A{
public function disName(){
echo 'BBB';
}
}
$a = new B;
$a -> disName(); //重寫A類
//輸出BBB
?>
9、接口和抽象類的區別是什麼?
1.抽象類中可以有非抽象的方法而接口中只能有抽象的方法
2.一個類可以繼承多個接口,而一個接口只能繼承一個抽象類
3.接口的使用時通過implements關鍵字進行,抽象類則是通過extends關鍵字來進行的
1、關鍵字:
接口:interface
實現implements
抽象類:abstract
繼承 extends。接口也可以繼承。
2、接口內不能有成員屬性,但是可以有類常量。 抽象類可以聲明各種類型成員屬性
3、接口裏不能有構造函數,抽象類可以有
4、接口中的方法只能是public,抽象類三種都有
5、一個類可以實現多個接口。但是卻只能繼承一個類
10、類中如何定義常量,如何類中調用常量,如何在類外調用常量
答:類中的常量也就是成員屬性常量,處理就是不會改變的量;定義常量的關鍵字是const;
例如:const PI = 3.14;
無論是類內還是類外常量的訪問和變量是不一樣的,常量不需要實例化對象,訪問常量的格式都是累名
價作用域操作符(雙::號來)來調用 。即:類名 :: 類常量名
self::PI; 只能在它本身內調用
static::PI;不能在class外調用
A::PI;不可以在內裏調用
例如:
class A{
const PI = 3.14159;
}
echo A::PI;//不能在類裏訪問
11、在PHP的面向對象中,類中的定義的析構函數是在()調用的
答:在代碼執行結束後調用
析構函數不是必須的,當一個類被實例化的時候(如果有)就會被調用,它是用來釋放內存的
spacify[插空]
string_format[字符串格式化]
strip[去除(多餘空格)]
strip_tags[去除html標籤]
truncate[截取]
upper[大寫]
wordwrap[行寬約束]
模板代碼
1.tol.class.php頁面
<?php
/*
編寫一個模板引擎類。
需求:
1、能替換{$name} <?php echo $name;?>
2、通過修改成員屬性 可以修改 左右定界符,模板文件的後綴。
3、通過魔術方法set、get可以設置(獲取)模板目錄template,編譯目錄template_c
4、設置兩個默認公共保留變量 {$jack} =>帥 {$version} =》v1.0
*/
class tpl{
private $_template = 'temmplate'; // 需要替換的文本
private $compile_file = 'template_c'; // 編譯後的文件
private $leftMr;
private $rightMr;
private $prefix = 'php';
private $_arr = [];
public function __construct(){
$this->a_rr = [
'title'=> 'smarty模板',
'jack' => '千斤頂',
'version' => 'v1.0'
];
}
public function assign($key,$val){
$this -> a_rr[$key] = $val;
}
//顯示文件
public function dispaly($path){
extract($this -> a_rr);
$filename = $this -> _template.'/'.$path;
$content = file_get_contents($filename);
$content = str_replace($this->left_delimiter,'<?php echo ',$content);
$content = str_replace($this->right_delimiter,';?>',$content);
$file_prefix = pathinfo($filename)['extension'];
if(!empty($this->prefix)){
$file_prefix = $this->prefix;
}
file_put_contents('template_c/'.pathinfo($path)['filename'].'_c.'.$file_prefix,$content);
include('template_c/'.pathinfo($path)['filename'].'_c.'.$file_prefix);
}
public function __get($name){
if(isset($this->$name)){
return $this->$name;
}
}
public function __set($name,$value){
$this->$name = $value;
}
}
?>
2.tpl.php頁面
<?php
require_once "tpl.class.php";
$Tpl = new tpl();
$Tpl -> left_delimiter = '{#';
$Tpl -> right_delimiter = '#}';
$Tpl -> assign('title','smarty模板');
$Tpl -> assign('name','我的標題');
$Tpl -> dispaly('index.html');
// var_dump($Tpl);
?>
3.html模板
/temmplate/index.html//目錄下的index.html頁面
<html>
<head>
<title>{#$name#}</title>
</head>
<body>
<h1 style="color:red;">{#$title#}</h1>
<hr/ color="red">
<h1>{#$version#}</h1>
<hr/ color="blue">
<h2>{#$jack#}</h2>
<hr/ color="green">
<h1>
<h1>{#$name#}</h1>
<hr/ color="pink">
<h1></h1>
</body>
</html>
/temlate_c/index.html或index.php//目錄下的index.html頁面
//生成以後的php頁面
<html>
<head>
<title><?php echo $name;?></title>
</head>
<body>
<h1 style="color:red;"><?php echo $title;?></h1>
<hr/ color="red">
<h1><?php echo $version;?></h1>
<hr/ color="blue">
<h2><?php echo $jack;?></h2>
<hr/ color="green">
<h1>
<h1><?php echo $name;?></h1>
<hr/ color="pink">
<h1></h1>
</body>
</html>
計算器代碼
1.index.php
<?php
//異常代碼處
class MyException extends Exception
{
public function Anomalous()
{
echo '<h1 style="background-color:red; ">異常頁面</h1>';
echo '<p style="background-color:yellow;">此文件位於:'.$this -> getFile().'</p>'; //返回發生異常信息的文件名
echo '<br/>';
echo '<p style="background-color:yellow;">用戶傳了一個不知道的符號:在 <b style="color:red;">'.$this -> getLine().' </b>行</p><br/>'; // 返回發生異常的代碼行號
}
}
//實現一個計算器 加,減 ,乘, 除
interface iJSQ {
const MA_JIA = '+';
const MA_JIAN = '-';
const MA_CHENG = '*';
const MA_CHU = '/';
//加
public function jia($three,$four);
//減
public function jiang($three,$four);
//乘
public function chen($three,$four);
//除
public function chu($three,$four);
}
class iCalculator implements iJSQ
{
public $three;
public $four;
public function Anomalous($three,$four,$make)
{
try{
if( !is_numeric($three) || !is_numeric($four) )
{
throw new MyException('兩個值一定是數值型的纔可以......');
}
switch ( $make ){
case self::MA_JIA:
return $this -> jia($three,$four);
break;
case self::MA_JIAN:
return $this -> jiang($three,$four);
break;
case self::MA_CHENG:
return $this -> chen($three,$four);
break;
case self::MA_CHU:
return $this -> chu($three,$four);
break;
default:
throw new MyException('用戶傳了一個不認識的符號過來但我不知道怎麼處理!!!!');
}
}catch( Exception $e ){
$e -> Anomalous();
$e -> getLine();
}
}
//加
public function jia($three,$four)
{
return $three + $four;
}
//減
public function jiang($three,$four)
{
return abs($three - $four);
}
//乘
public function chen($three,$four)
{
return abs($three * $four);
}
//除
public function chu($three,$four)
{
return abs($three / $four);
}
}
$my = new iCalculator();
echo '結果是:'.$my -> Anomalous(91,20,'/');
?>
2.jsq.php
<?php
interface iCounter
{
// 加
public function jia($One,$two);
// 減
public function jiang($three,$four);
// 乘
public function cheng($five,$six);
// 除
public function chu($seven,$eight);
}
class arithmetic implements iCounter
{
public function handle($One,$two,$mark){
try{
if(!is_numeric($One) || !is_numeric($two)){
throw new Exception('不是數字');
}
switch($mark){
//加法
case '+':
if($One == 0 && $two == 0)
{
throw new Exception('數字不能0');
}else{
return $this->jia($One,$two);
}
break;
//減法
case '-':
if($One == 0 && $two == 0)
{
throw new Exception('數字不能爲0');
}else{
return $this->jiang($One,$two);
}
break;
//乘法
case '*':
if($One ==0 && $two == 0)
{
throw new Exception('數字不能爲0');
}else{
return $this->cheng($One,$two);
}
break;
//除法
case '/':
if($One==0 && $two==0)
{
throw new Exception('除數與被除數都不能爲0');
}else{
return $this->chu($One,$two);
}
break;
}
}catch(Exception $e){
echo $e->getMessage().',錯誤所在行數:'.$e->getLine();
}
}
// 加法的方法
public function jia($One,$two)
{
return $One + $two;
}
// 減法的方法
public function jiang($One,$two)
{
return $One - $two;
}
// 乘法的方法
public function cheng($One,$two)
{
return $One * $two;
}
// 除法的方法
public function chu($One,$two)
{
return $One / $two;
}
}
$jisuanqi = new arithmetic;
echo $jisuanqi->handle('12','5','*');
?>
3.數據庫代碼
<?php
class mysql
{
public $link;
public $name;
public $db_local;
public $db_pwd;
public $user_error;
public function __construct($db_local,$db_user,$db_pwd,$db_name)
{
//這個可以通過構造方法來去讀取我們的數據庫配置文件
$this->link = @mysql_connect($db_local,$db_user,$db_pwd) or die('數據庫連接失敗');
mysql_select_db($db_name,$this->link);
mysql_set_charset('utf8',$this->link);
}
public function findOne( $tabname, $id )
{
$sql = "select * from {$tabname} where id = {$id} ";
$result = mysql_query($sql,$this->link);
$list = [];
if( $result && mysql_affected_rows() > 0 ){
while( $row = mysql_fetch_assoc($result) )
{
$list[] = $row;
var_dump($list);
}
return $list;
}else{
return [];
}
}
}
$mysql = new mysql('localhost','root','root','hello');
$aList = $mysql->findOne('mysql',1);
?>
4.作業
<table border="1"width="500" height="500" align="center">
<tr>
<td align="center">
<h1 style="color:green;font-size:30px">作 業</h1>
一、編寫一個生成金字塔的功能
1、一個表單提交 用於錄入金字塔層數<br/>
<form action="" method="post">
<input type="number" name="text" size="10" />
<input type="submit" value=" 顯示 " name="Submit" />
</form>
<?php
class pyramid{
public function __construct($empty,$value){
if(!empty($_POST['text']) ) {
//打印正立金字塔
for( $i = 1; $i <= $empty; $i++ ){
//打印每一層的空格數
for( $j = $empty; $j > $i; $j-- ) {
echo " ";
}
//打印每一層的星星個數
for( $k = 1; $k <= $i*2-1; $k++ ) {
echo $value;
}
echo '<br/>';
}
echo '<hr/>';
}else{
echo '<b style="color:green;">你個二逼,只能輸入數字,不能輸入中文,英文,以及空格哦,下次記住了,不要再輸入那些沒用的了,我不識別</b>';
}
}
}
$empty = isset($_POST['text']) ? $_POST['text'] : 1 ;
$construct = new pyramid($empty,'<b style="color:red;">*</b>');
echo '<br/>';
echo '二、定義一個字符串(純數字)生成類:(目的用於生成驗證碼)<br/>';
class code
{
public $nubmer;
public function __construct($nubmer){
for( $one = 0; $one < $nubmer; $one++ ){
echo '<span style="font-weight:700;font-size:28px;color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).');">'.mt_rand(0,9).'</span>';
}
}
}
$strin = new code(4);
echo '<hr/>';
/* $nubmer = 4;
$code = '0123456789';
for( $one = 0; $one < $nubmer; $one++ ){
$string = $code{mt_rand(0,strlen($code)-1)};
echo $string;
}*/
echo '三、定義一個字符串生成類:(目的用於生成驗證碼)<br/>';
class randnameP{
public $cedo = 4;
public $codea = 'c';
public function fandunam(){
switch( $this-> codea ){
case 'a':
$scandir = "0123456789";
break;
case 'b':
$scandir = "0123456789abcdefghijklmnopqrstuvwxyz";
break;
case 'c':
$scandir = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
break;
default :
$scandir = "0123456789";
break;
}
for( $i = 0; $i< $this->cedo; $i++ ){
echo '<span style="font-weight:700;font-size:28px;color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).');">'.$scandir[mt_rand(0,strlen($scandir)-1)].'</span>';
}
}
}
$string = new randnameP();
$string -> fandunam();
echo '<hr/>';
echo '四、用面向對象的方法輸出一個表格<br/>
1、成員屬性:id,name,sex,nation,birthdy<br/>
2、把對象存入數組<br/>
3、遍歷數組生成表格<hr/>';
class xtable
{
public $id;
public $name;
public $sex;
public $nation;
public $birth;
public function __construct($id,$name,$sex,$nation,$birth){
$this -> id = $id;
$this -> name = $name;
$this -> sex = $sex;
$this -> nation = $nation;
$this -> birth = $birth;
}
}
$xtable2 = new xtable('2','喻恆勇','男','火星','1111-10-1');
$array = [$xtable2];
echo '<table border="1"width="300"height="50">
<tr>
<th>id</th>
<th>姓名</th>
<th>性別</th>
<th>國家</th>
<th>出生日期</th>
</tr>';
foreach($array as $key => $value){
echo '<tr>
<td>'.$value->id.'</td>
<td>'.$value->name.'</td>
<td>'.$value->sex.'</td>
<td>'.$value->nation.'</td>
<td>'.$value->birth.'</td>
</tr>
</table>';
}
?>
</td>
</tr>
</table>
4.分頁
<?php
/* ================================================
* @類名: Page *
* @參數: $myde_total 總記錄數 *
* $myde_size 頁顯示的記錄數 *
* $myde_page 當前頁 *
* @功能: 分頁實戰 *
*=================================================
*/
class Page {
public $myde_total; //總記錄數
public $myde_size; //每頁顯示的多少條
public $myde_page_count; //總頁數
public $myde_i; //當前第幾頁
public $myde_en = 2; //頁面兩邊的數字
/*===================================
* *
* 頁面顯示 *
* *
* 構造函數 *
* *
*====================================*/
public function __construct($myde_total ,$myde_size, $myde_i ) {
$this -> myde_total = $myde_total;
$this -> myde_size = $myde_size;
$this -> myde_page_count = ceil($this -> myde_total / $this->myde_size);
if($myde_i < 0){
$this -> myde_i = 1;
}else if($myde_i > $this->myde_page_count){
$this -> myde_i = $this->myde_page_count;
}else{
$this -> myde_i = $myde_i;
}
}
//獲取首頁
public function myde_home()
{
if ($this -> myde_i > 1) {
return "<a href='page.php'>首頁</a>";
}
return "<p>首頁</p>";
}
//獲取上一頁
public function myde_prev()
{
if( $this->myde_i >1 ){
return '<a href="page.php?page='.($this->myde_i-1).'">上一頁</a>';
}
return '<p>上一頁</p>';
}
/**
*
*獲取下一頁
*/
public function myde_next()
{
if( $this->myde_i < $this-> myde_page_count ){
return '<a href="page.php?page='.($this -> myde_i + 1).'">下一頁</a>';
}
return '<p>下一頁</p>';
}
//獲取尾頁
public function myde_last()
{
if ( $this -> myde_i < $this -> myde_page_count ) {
return '<a href="page.php?page='.($this->myde_page_count).'" >尾頁</a>';
}
return "<p>尾頁</p>";
}
//實現多少頁
public function code()
{
return '<p class="pageRemark">共<b>'.$this->myde_page_count.'</p>頁';
}
//獲取每一條數據
public function sum()
{
return '<b>'.$this -> myde_total.'</b>條數據</p>';
}
public function start()
{
$achieve = '';
if( $this -> myde_i - $this -> myde_en > 1 )
{
$achieve .= "<p class='pageEllipsis'>...</p>";
for( $i = $this -> myde_i - $this -> myde_en; $i < $this -> myde_i;$i++)
{
$achieve .= '<a href="page.php?page='.$i.'">'.$i.'</a>';
}
}else{
for( $i =1;$i <= $this->myde_i-1;$i++){
$achieve .= '<a href="page.php?page='.$i.'">'.$i.'</a>';
}
}
$achieve .= '<a href="" class="cur">'.$this -> myde_i.'</a>';
if( $this-> myde_i + $this -> myde_en < $this -> myde_page_count ){
for( $k = $this -> myde_i + 1; $k <= $this -> myde_i + $this -> myde_en;$k++ ){
$achieve .= '<a href="page.php?page='.$k.'">'.$k.'</a>';
}
$achieve .= "<p class='pageEllipsis'>...</p>";
}else{
for( $j = $this -> myde_i + 1; $j <= $this -> myde_page_count; $j++ ){
$achieve .= '<a href="page.php?page='.$j.'">'.$j.'</a>';
}
}
return $achieve;
}
//用來顯示
public function Show()
{
$paged = '<div id="page">';
$paged .= $this -> myde_home();
$paged .= $this -> myde_prev();
$paged .= $this -> start();
$paged .= $this -> myde_next();
$paged .= $this -> myde_last();
$paged .= '</div>';
return $paged;
}
}
$pageted = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$pad = new Page(50,5,$pageted);
echo $pad -> Show();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
p{margin:0}
#page{
height:40px;
padding:20px 0px;
}
#page a{
display:block;
float:left;
margin-right:10px;
padding:2px 12px;
height:24px;
border:1px #cccccc solid;
background:#fff;
text-decoration:none;
color:#808080;
font-size:12px;
line-height:24px;
}
#page a:hover{
color:#077ee3;
border:1px #077ee3 solid;
}
#page a.cur{
border:none;
background:#077ee3;
color:#fff;
}
#page p{
float:left;
padding:2px 12px;
font-size:12px;
height:24px;
line-height:24px;
color:#bbb;
border:1px #ccc solid;
background:#fcfcfc;
margin-right:8px;
}
#page p.pageRemark{
border-style:none;
background:none;
margin-right:0px;
padding:4px 0px;
color:#666;
}
#page p.pageRemark b{
color:red;
}
#page p.pageEllipsis{
border-style:none;
background:none;
padding:4px 0px;
color:#808080;
}
.dates li {font-size: 14px;margin:20px 0}
.dates li span{float:right}
</style>
</head>
</body>
</html>
5.域名修改
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if( preg_match_all('/\/[0-2]+\/[0-9]+\.html$/',$url) )
{
preg_match_all('/[0-9]+/',$url,$match);
$url = 'index.php?type='.$match[0][0].'&id='.$match[0][1];
var_dump($url);
echo '<script>location.href="'.$url.'"</script>';
}
$url = 'http://study.com/index.php/12/2.html';
if( preg_match_all('/\/[0-2]+\/[0-9]+\.html$/',$url) )
{
preg_match_all('/[0-9]+/',$url,$match);
preg_match('/http[s]?\:\/\/([a-zA-Z])+.[com|cn|net|org]+[\/\w*]+.[php]+/',$url,$match2);
$url = $match2[0];
$url .= '?type='.$match[0][0].'&id='.$match[0][1];
var_dump($url);
}
6.生成數據庫字典
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自動生成數據字典</title>
<style>
body,td,th {font-family:"宋體"; font-size:12px;}
table,h1,p{width:960px;margin:0px auto;}
table{border-collapse:collapse;border:1px solid #CCC;background:#efefef;}
table caption{text-align:left; background-color:#fff; line-height:2em; font-size:14px; font-weight:bold; }
table th{text-align:left; font-weight:bold;height:26px; line-height:26px; font-size:12px; border:1px solid #CCC;padding-left:5px;}
table td{height:20px; font-size:12px; border:1px solid #CCC;background-color:#fff;padding-left:5px;}
.c1{ width: 150px;}
.c2{ width: 150px;}
.c3{ width: 80px;}
.c4{ width: 100px;}
.c5{ width: 100px;}
.c6{ width: 300px;}
select{
margin-left: 620px;
}
</style>
<!--
SELECT * FROM information_schema.`TABLES` WHERE table_name = 'tasks' AND table_schema = 'dbname';
SELECT * FROM information_schema.`COLUMNS` WHERE table_name = 'tasks' AND table_schema = 'dbname';
-->
</head>
<body style="background-color:#aaa;">
<h1 style="text-align:center;color:red;width:100px">數據字典</h1>
<p style="text-align:center;margin:20px auto;">生成時間:<?php date_default_timezone_set('Asia/shanghai'); echo date('Y-m-d H:i:s',time())?></p>
<form method="post">
<select id="option" name="select">
<?php
$link = @mysql_connect('localhost','root','root');
if(mysql_errno()){
file_put_contents('erron.log',mysql_error());
}
mysql_set_charset('utf8');
$zidian = mysql_query("select * from information_schema.TABLES group by TABLE_SCHEMA having TABLE_SCHEMA not in('mysql','performance_schema','information_schema')");
while(($qude = mysql_fetch_assoc($zidian)) != false){
?>
<option value="<?php echo $qude['TABLE_SCHEMA']?>"<?php if(!empty($_POST['select']) && $_POST['select']==$qude['TABLE_SCHEMA']){echo 'selected="selected"';}?>><?php echo $qude['TABLE_SCHEMA']?></option>
<?php }?>
</select>
<input type="submit" name="sub" value=" query "/>
</form> <hr/>
<?php
$rest = !empty($_POST['select']) ? $_POST['select'] : 'blog';
$query = mysql_query("select * from information_schema.tables where table_schema ='{$rest}'");
while(($fech = mysql_fetch_assoc($query)) != false){
?>
<table border="1" cellspacing="0" cellpadding="0" align="center">
<caption>表名:<?php echo $fech['TABLE_NAME'];?> </caption>
<tbody>
<tr>
<th>字段名</th>
<th>數據類型</th>
<th>默認值</th>
<th>允許非空</th>
<th>自動遞增</th>
<th>備註</th>
</tr>
<?php
$sql_regcase = mysql_query("select * from information_schema.columns where table_name ='{$fech['TABLE_NAME']}'");
while(($mt_srand = mysql_fetch_assoc($sql_regcase)) !=false){
?>
<tr>
<td class="c1"><?php echo $mt_srand['COLUMN_NAME'];?></td>
<td class="c2"><?php echo $mt_srand['COLUMN_TYPE'];?></td>
<td class="c3"><?php echo $mt_srand['COLUMN_DEFAULT'];?></td>
<td class="c4"><?php echo $mt_srand['IS_NULLABLE'];?></td>
<td class="c5"><?php echo $mt_srand['EXTRA'];?></td>
<td class="c6"><?php echo $mt_srand['COLUMN_COMMENT'];?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</body>
</html>
7.數據庫作業
<?php
class MySQL
{
public $aFields = []; // 存儲表裏面所有字段
protected $link; // 數據庫連接
private $_array = [
'db_host' => 'localhost', //主機地址
'db_user' => 'root', //用戶名
'db_pwd' => 'root',//用戶密碼
'db_name' => 'hello',//數據庫名
'db_charset' => 'utf8'//數據庫編碼
];
private $_tablname; //表名
private $_tabPre = 'pc_'; //表名前綴
private $_lj; //表主鍵字段
//構造
public function __construct( $tabname ){
extract($this->_array);
$this->link= @mysql_connect($db_host,$db_user,$db_pwd) or die('數據庫連接失敗');//數據庫連接
@mysql_select_db($db_name,$this->link);//數據庫名字
@mysql_set_charset($db_charset,$this->link);
$this->_tablname = $this->_tabPre.$tabname;
$this->getTableFields($this->_tablname);
if( mysql_errno() ){
$error = "錯誤信息是: ".mysql_errno().":錯誤信息是:".mysql_error();//錯誤日誌
}else{
return false;
}
}
/**
* 更新記錄
* @param number $id
* @param array $post
*/
public function update($id, array $post ){
$sql = "UPDATE $this->_tablname SET ";
$set = [];
foreach($post as $key => $value){
$set[] = "`{$key}`='{$value}'";
}
$sql .= implode(',', $set);
$sql .= " WHERE $this->_lj = {$id}";
echo $sql;
$sest = mysql_query($sql);
if( $sest && mysql_affected_rows() ){
return mysql_affected_rows();
}else{
return false;
}
}
/**
* 獲取單條記錄
* @param number $id
* @return array
*/
public function find($id){
$sql = "SELECT * FROM $this->_tablname WHERE {$this->_lj}='{$id}'";//獲取單條記錄
//echo $sql;
$sest = mysql_query($sql);
$rows = [];
if( $sest && mysql_affected_rows()>0 ){
$rows = mysql_fetch_assoc($sest);
}else{
return $rows;
}
}
/**
* 插入數據
* @param array $post
*/
public function insert(array $post){
$query = '';
$query .= "insert into `$this->_tablname`";
$query .= "(`".implode('`,`', array_keys($post))."`)";
$query .= ' values ';
$query .= "('".implode('\',\'', array_values($post))."')";
//var_dump($query);
$sest = mysql_query($query,$this->link);
if( $sest && mysql_affected_rows() > 0 ){
return mysql_insert_id();
}else{
return false;
}
}
/**
* 獲取全部記錄
* @param array $post
* @return arraylist
*/
public function findAll(array $aCondition=[]){
$sql = $this-> handleCondition($aCondition);
//echo $sql;
//return $sql;
//$sql ="SELECT title,content FROM pc_ddg ORDER BY id DESC LIMIT 1,4;";
$Ambigous = mysql_query($sql);
//var_dump($Ambigous);
$words = [];
if($Ambigous && mysql_affected_rows() > 0){
while($word = mysql_fetch_assoc($Ambigous) ){
$words[] = $word;
}
return $words;
}else{
return false;
}
}
/**
* 刪除記錄
* @param number $id
*/
public function delete( $id ){
$sql = "delete from $this->_tablname where {$this->_lj} = {$id}";
echo $sql;
$sest = mysql_query($sql);
if( $sest == mysql_affected_rows() ){
return mysql_affected_rows();
}else{
return false;
}
}
/**
* 處理查詢條件
* @param array $aCondition []
*/
protected function handleCondition(array $aCondition){
if( !empty($aCondition) ){
$sele = '*';
$limit = $order = '';
foreach ($aCondition as $key=>$value){
$key = strtolower($key);
switch ($key){
case 'select':
$sele = $value;
break;
case 'sort':
$order = ' order by '.$value;
break;
case 'limit':
$limit = ' limit '.$value;
break;
}
}
$sql = "SELECT $sele FROM $this->_tablname{$order}{$limit}";
}else{
$sql = "SELECT * FROM $this->_tablname";
}
return $sql;
}
/**
* 獲取表主鍵字段
* @return Ambigous <>|string
*/
protected function getTableFields(){
$sql = "desc $this->_tablname";
$sest = mysql_query($sql);
if( $sest && mysql_affected_rows() > 0 ){
while ($row = mysql_fetch_assoc($sest)) {
if( $row['Key'] == 'PRI' )
$this->_lj = $row['Field'];
$this->aFields[] = $row['Field'];
}
}else{
return false;
}
}
}
$my = new MySQL('dd');
//插入數據
//$my -> insert(['title'=>'張三','content'=>'李四','created'=>'2017-4-20 12:00:00']);
//修改數據
//var_dump($my -> update(4,['title'=>'李四']));
//刪除
//var_dump($my->delete(4));
//查詢單條
//var_dump($my->find(3));
//查詢全部
var_dump($my -> findAll(['select'=>'title,content,created','limit'=>'0,4','sort'=>'id DESC']));