帳號登錄
帳號:
密碼:
記住我 | 忘記密碼 | 帳號註冊
網站導覽
模組開發 : 資料庫操作與類別-CRUD
作者 elie 於 2010年09月08日 22:42:00 (9778 次閱讀)

原始出處 http://www.xoops.org/modules/mediawiki/index.php/DB_Operations_and_Classes

 

CRUD

在資料庫中有四種常用函式:新增(Create),讀取(Read),更新(Update),刪除(Delete);通常會被簡寫為CRUD。在之前的介紹中我的焦點在Read 與Create,接下來我將為這四個函式提供範例。

Create

$query = "Insert into ".$xoopsDB->prefix("tutorial_myform")." (name, address, telephone, email) values ('$name', '$address', '$tel', '$email' )";
$res=$xoopsDB->query($query);
if(!$res) {
echo "error: $query";
}

Read

$query = $xoopsDB->query(' SELECT * FROM ' . $xoopsDB->prefix('tutorial_myform') . " WHERE id='$myid' ");
$myrow = $xoopsDB->fetchArray($query);
$name = $myrow['name'];
$address = $myrow['address'];
$telephone = $myrow['telephone'];
$email = $myrow['email'];

Update

$query = "UPDATE ".$xoopsDB->prefix("tutorial_myform")." SET deff=1 WHERE sid='$newdef' ";
$res=$xoopsDB->query($query);
if(!$res) echo "error: $query";

Delete

$query = "Delete from ".$xoopsDB->prefix("tutorial_myform")." WHERE sid='$test' ";
$res=$xoopsDB->query($query);
if(!$res) {
echo "error: $query";
}

Create,update 與delete,在執行結束後會回傳TRUE 或FALSE 並設定為$res 的值,我們可以用簡單的if 判斷式知道資料庫變動時是否有錯誤發生。

重要:Create,update 與delete 時需要你用$_POST 取得資料。如果你使用其他方式如GET 或SESSION 等的話,你就需要使用不同的條件式了,這個不同的條件式已經內建在XOOPS 中。在xoops.org 討論區已有相關討論,如果你想了解更多的話搜尋一下就可以了。

$query = "Delete from ".$xoopsDB->prefix("tutorial_myform")." WHERE sid='$test' ";
$res=$xoopsDB->queryF($query);
if(!$res) {
echo "error: $query";
}

更多討論請見dev.xoops.org:Using The DatabaseDatabase Tables


可列印模式 轉寄給朋友

The XOOPS organisation ("XOOPS") is committed to protecting the privacy of users of the XOOPS.org sites.
The website used Ver.2.4.5 POWERED BY XOOPS PROJECT.