Tip 1: MySQL 連結 Class
[php]class DB {
function DB() {
$this->host = "localhost"; // your host
$this->db = "myDatabase"; // your database
$this->user = "root"; // your username
$this->pass = "mysql"; // your password
$this->link = mysql_connect($this->host, $this->user,
$this->pass);
mysql_select_db($this->db);
}
}
// 在你需要開始使用資料庫的地方(記得先include起來)
$db = new $DB;[/php]
只要更改變數就可以馬上套用,讓你的程式碼更乾淨。
Tip 2: 安全性 (Dealing with Magic Quotes)
magic quotes .... 不大懂
SQL injection 注入:在使用者能輸入的地方動手腳,如文字方塊
regular expressions 利用正規表示式檢查變數
Tip 3: 使用mysql_real_escape_string安全的查詢資料庫 (Safely Query Database with mysql_real_escape_string)
[php]function escapeString($post) {
if (phpversion() >= '4.3.0') {
return array_map('mysql_real_escape_string',$post);
} else {
return array_map('mysql_escape_string',$post);
}
}[/php]
Tip 4: 除錯 (Debugging)
[php]//禁用錯誤報告
error_reporting(0);
//報告運行時錯誤
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//報告所有錯誤
error_reporting(E_ALL);
//印出物件、陣列內容
print_r($result); exit;[/php]
Tip 5: 編寫函數和類別 - Writing Functions (and Classes)
Tip 6: 單引號和雙引號 - Single and double quotes
$abc = 1; echo '$abc'; //印出$abc echo "$abc"; //印出1 只是單純字串用單引號效率會比較好。
Tip 7: 撰寫風格 - Problems of style 讓寫出來的程式碼更易讀、易除錯。
Tip 8: 三元運算符 - Ternary Operator
讓程式碼精簡、更快(?) echo ( true ? 'true' : false ? 't' : 'f' );
Tip 9: 安全查詢 - Safe Queries
[php]// returns an array of records
function fetchArray($query='')
{
if ($result = safeQuery($query)) {
if (mysql_num_rows($result) > 0) {
while ($arr = mysql_fetch_assoc($result)) $rows[] = $arr;
return $rows;
}
}
return false;
}
// returns a single record
function fetchRecord($query='')
{
if ($row = safeQuery($query)) {
if (mysql_num_rows($row) > 0) {
return mysql_fetch_assoc($row);
}
}
return false;
}
Now, with one simple line of code we can perform our query to return our predicted results.
$results = fetchArray("SELECT id,field1 FROM records");
// sample output results
if (!$results) {
echo 'No results.';
} else {
// loop the data
foreach ($results as $result) {
echo $result['id'] . ' ' . $result['field1'];
}
}[/php]
Tip 10: 成功的策略 - A Strategy for Success
用紙筆規劃好你的想法!
沒有留言:
張貼留言