css

2013年11月5日 星期二

PHP’s PDO

PDO (PHP Data Object) 提供了一個 Abstraction Layer 來操作資料庫


連接DB

  1. define('DB_NAME','mydb');
  2. define('DB_USER','username');
  3. define('DB_PASSWD','userpwd');
  4. define('DB_HOST','localhost');
  5. define('DB_TYPE','mysql');
  6. try{
  7.    $dbh = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWD,
  8.                    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
  9.    $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); //錯誤訊息提醒
  10.    }
  11. catch (PDOException $e){
  12.      echo 'Error!: ' . $e->getMessage() . '<br />';
  13.      }


  • PDO 是 Abstraction Layer 所以就算更換儲存媒介,需要花的功夫比起來是最少的;將DB_TYPE改掉,即可移到不同DB使用。
  • PDO 可以透過 PDO::setAttribute 來決定連線時的設定,像是 Persistent Connection, 回傳錯誤的方式(Exception, E_WARNING, NULL)。甚至是回傳欄位名稱的大小寫…等等 
      PDO Drivers
      Connections and Connection management
      PDO::setAttribute
      PDOException 



查詢

    ex1:

  1. $sql = 'select ArticleDate,ChineseTitle,SubChineseTitle from Article where 
           ArticleDate=:seldate';
  2. $sth = $dbh->prepare($sql);
  3. $sth ->execute(array(':seldate' => $seldate));


    ex2:
     
  1. $sth = $dbh->prepare('insert into Article(ArticleDate,Type,EngTitle,ChineseTitle)values (:date,:type,:et,:ct)');
  2. $sth->bindParam(':date',$seldate);
  3. $sth->bindParam(':type',$_POST["type"], PDO::PARAM_STR,15);
  4. $sth->bindParam(':et',$_POST["EngTitle"], PDO::PARAM_STR,30);
  5. $sth->bindParam(':ct',$_POST["ChineseTitle"], PDO::PARAM_STR,30);
  6. $sth->execute() 
  • PDO 支援 Bind Column 的功能,除了基本的 Prepare, Execute 以外,也可以 Bind 單一欄位,並且指定欄位型態。
     Prepared statements and stored procedures
     Predefined Constants   PDO::PARAM
     PDOStatement


取資料

     ex1:
  1. $obj = $sth->fetch(PDO::FETCH_ASSOC);
  2. echo $obj["ArticleDate"];
  3. echo $obj["ChineseTitle"];
  4. echo $obj["SubChineseTitle"];
   
     ex2:
    
  1. $obj = $sth->fetch(PDO::FETCH_OBJ);
  2. echo $obj->ChineseTitle
  3. echo $obj->SubChineseTitle
      
      PDOStatement::fetch
      PDOStatement::fetchAll


參考資料
PDO vs. MySQLi: Which Should You Use?
淺談 PHP-MySQL, PHP-MySQLi, PDO 的差異
PHP MYSQL PDO
[解決] Undefined class constant 'MYSQL_ATTR_INIT_COMMAND'
PDO 基本用法
Comparison of PHP Database Abstraction Classes

2013年10月28日 星期一

CentOS 安裝 Xdebug

安裝前 phpinfo 內 zend圖案









1. 用 pecl 安裝

安裝指令  sudo pecl install xdebug

錯誤訊息 :  phpize not found (找不到此指令)

網路上搜尋後,有人說在Debian/Ubuntu要先裝 php5-dev



2.安裝 php dev

搜尋yum search php5-dev   =>no matches found(在centos內沒有php5-dev)

搜尋yum search php-dev  => php-devel.x86_64

安裝 yum install php-devel



3.再次用pecl 安裝xdebug

  pecl install xdebug   安裝成功



4.php.ini 設定 zend_extension=xdebug.so  

   官方網站說要使用完整路徑

   先搜尋安裝位置 find / -name xdebug.so

   找到檔案位置 /usr/lib64/php/modules/xdebug.so

   修改php.ini  :  vim /etc/php.ini 
    到檔案尾端加入一行
 
     zend_extension="/usr/lib64/php/modules/xdebug.so"

     存檔離開 :wq

官網提示
Note: You should ignore any prompts to add "extension=xdebug.so" to php.ini — this will cause problems.



5. 重新啟動WEB Server

     /etc/rc.d/init.d/httpd restart



6.到 phpinfo 頁面確認

   安裝後 phpinfo 內圖樣 多了一行with Xdebug ...
 



Xdebug 官方網站安裝說明
http://xdebug.org/docs/install



補充:要已安裝 php-pear  ,才能用 pecl 指令

2013年10月17日 星期四

PHP session.save_path

PHP session 設定參數 ( php.ini)


session.save_path = "/var/lib/php/session"  (centos環境下路徑)


Runtime Configuration 



PHP session 暫存檔過多的注意事項

error_reporting() php.ini

error_reporting    設定回報哪些類型的php錯誤

 int error_reporting ([ int $level ] )

此函式設定php執行的錯誤回報等級,若無指定level層級,則使用目前層級(定義在php.ini內 error_reporting)

level 等級可以用數字或名稱來指定;

但隨著php更新,新的error level 等級加入,用數字的表示error level 可能造成錯誤的結果,

保險的方法還是用名稱設定 error level




原函式定義
http://php.net/manual/en/function.error-reporting.php

錯誤等級的定義
http://www.php.net/manual/en/errorfunc.constants.php

位元運算
http://www.php.net/manual/en/language.operators.bitwise.php

Runtime錯誤回報設定
http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting



在 php.ini 內 (約513行)  

error_reporting  =  E_ALL & ~E_NOTICE




2013年8月6日 星期二

sql join

toys
toy_id toy
1 hula hoop
2 balsa glider
3 toy soldiers
4 harmonica


boys
boy_id boy
1 Davey
2 Bobby
3 Richie



交叉連結 CROSS JOIN ,卡笛生乘積,交叉乘積,不是連結NO JOIN



SELECT t.toy, b.boy                                      SELECT t.toy, b.boy

FROM toys t                                or               FROM toys t,boys b

CROSS JOIN  boys b


toy boy
hula hoop Davey
hula hoop Bobby
hula hoop Richie
balsa glider Davey
balsa glider Bobby
balsa glider Richie
toy soldiers Davey
toy soldiers Bobby
toy soldiers Richie
harmonica Davey
harmonica Bobby
harmonica Richie



內部連結 INNER JOIN




SELECT somecolumns

FROM table1

INNER JOIN

table2

ON somecondition;


利用條件判斷的比較運算子,結合兩份資料表的紀錄;

只有連結紀錄符合條件時,才會回傳資料欄。




內部連結:Equijoin :檢視相等性的內部連結



SELECT b.boy,t.toy

from boys b

INNER JOIN

toys t

ON b.toy_id=t.toy_id



boys
boy_idboytoy_id
1Davey3
2Bobby2
3Richie1

toys
toy_id toy
1 hula hoop
2 balsa glider
3 toy soldiers
4 harmonica


equijoin   ON b.toy_id=t.toy_id
boytoy
Richiehula hoop
Bobbybalsa glider
Daveytoy soldiers



內部連結:Non-equijoin :檢查非相等性的內部連結

SELECT b.boy,t.toy

from boys b

INNER JOIN

toys t

ON b.toy_id <> t.toy_id


non-equijion  ON b.toy_id <> t.toy_id
boytoy
Daveyhula hoop
Bobbyhulahoop
Daveybalsa glider
Richiebalsa glider
Bobbytoy soldiers
Richietoy soldiers
Daveyharmonica
Bobbyharmonica
Richieharmonica




內部連結:自然聯結 Natural Join

利用相同資料欄名稱的內部聯結

select boys.boy,toys.toy

from boys

natural join

toys


natural join 
boytoy
Richiehula hoop
Bobbybalsa glider
Daveytoy soldiers

2013年7月30日 星期二

SQL 外鍵(foreign key)

綱要(schema)
對資料表內的資料描述(資料欄與資料表),以及任何相關物件和各種連結方式的描述。

外鍵(foreign key)
資料表裡的某一欄,它參照到另一個資料表的主鍵。

外鍵可能與它參照的主鍵名稱不同。
外鍵使用的主鍵,也被稱為父鍵(parent key),主鍵所在的的資料表,又稱為父資料表(parent table)

外鍵能用於確認甲資料表裡的紀錄與乙資料表能夠對應。

外鍵值可以是NULL,即使主鍵值不可為NULL。

外鍵值不需要獨一無二,通常都沒有唯一性。

外鍵值為NULL,表示在父資料表裡沒有相符的主鍵。

可透過限制條件(constraint)確認外鍵包含有意義,已儲存在父資料裡面的值。


外鍵限制
參照完整性 (referential integrity)
插入外鍵欄位的值,必需已經存在父資料表的來源欄位裡。

使用外鍵參照父資料表裡面某個獨一無二的值,
外鍵不見得必須是父資料表的主鍵,但必須具有唯一性。



MYSQL 內設定 foreign key需滿足

1.該資料表類型需設為InnoDB




2.外鍵欄位須建立索引類型index







3.確認外鍵的資料型態需與父鍵相同後,在關聯查看內設定constraint


        選擇關聯的表及欄位                    自訂約束名稱                     選擇reference_option



reference_option:
 
CASCADE
Whenever rows in the master (referenced) table are deleted (resp. updated), the respective rows of the child (referencing) table with a matching foreign key column will get deleted (resp. updated) as well. This is called a cascade delete (resp. update[2]).
RESTRICT
A value cannot be updated or deleted when a row exists in a foreign key table that references the value in the referenced table. Similarly, a row cannot be deleted as long as there is a reference to it from a foreign key table.
NO ACTION
NO ACTION and RESTRICT are very much alike. The main difference between NO ACTION and RESTRICT is that with NO ACTION the referential integrity check is done after trying to alter the table. RESTRICT does the check before trying to execute the UPDATE or DELETE statement. Both referential actions act the same if the referential integrity check fails: the UPDATE or DELETE statement will result in an error.
SET NULL
The foreign key values in the referencing row are set to NULL when the referenced row is updated or deleted. This is only possible if the respective columns in the referencing table are nullable. Due to the semantics of NULL, a referencing row with NULLs in the foreign key columns does not require a referenced row.
 
 
alter table 增加constraint語法 

ALTER TABLE tbl_name
    ADD [CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]