PHP codeigniter标准crud模型

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP codeigniter标准crud模型相关的知识,希望对你有一定的参考价值。

<?php
class Crud extends Model {
/*create the array to pass to the views*/
var $data = array();
var $form = array();
var $controller;
function Crud()
{
// Call the Model constructor
parent::Model();
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('errors');
$this->load->library('validation');
$this->load->database();
$this->load->model('display');

$this->form =
array
('sites' => array
(
'id' => array('ID number of this site',
'readonly', 'numeric'),
'name' => array('Name of site', 'textarea',
'alpha_numeric'),
'url' => array('Qualified URL,
eg http://www.example.com', 'input', ''),
'un' => array('username to log in to site',
'input', 'numeric|xss_clean'),
'pw' => array('password for site', 'input',
'xss_clean'),

'client1' => array('Main client',
'dropdown', '', 'people' ),
'client2' => array('Second client', 'dropdown',
'', 'people'),
'admin1' => array('First admin', 'dropdown',
'', 'people'),
'admin2' => array( 'Second Admin', 'dropdown',
'', 'people'),
'domainid' => array('Domain name', 'dropdown',
'numeric', 'domains'),
'hostid' => array( 'Host', 'dropdown',
'numeric', 'hosts'),
'submit' => array( 'Enter details', 'submit', 'mumeric')
),
'domains' => array
(
'id' => array('ID number of this domain',
'hidden', 'numeric'),
//etc etc etc!!


/*this function lists all the entries in a database table on one page. Note that every db table must have an 'id' field and a 'name' field to display!
This page is a jumping-off point for the other functions - ie to create, read, update or delete an entry.
When you've done any of these, you are returned to this page. It has a 'message' parameter, so you can return with a message - either success or failure.*/
function showall($controller='', $message = '', $test ='no')
{
$result = '';
$mysess = $this->session->userdata('session_id');
$mystat = $this->session->userdata('status');
if(!$this->db->table_exists($controller))
{
$place = __FILE__.__LINE__;
$outcome = "exception:$place:looking for table $controller: it doesn't exist'";
/*test block: what if there is no controller by that name?*/
if($test =='yes')
{
return $outcome;
}
else{
$this->failure($outcome, 'sites');
}
}

/*end test block*/
$this->db->select('id, name');
$query = $this->db->get($controller);
if ($query->num_rows() > 0)
{
$result .= "<table class='table'>";

$result .= "<tr><td colspan='3'><h3>$controller</h3></
td></tr>";
$result .= "<tr><td colspan='3' class='message'>
$message</td></tr>";
$result .= "<tr><td colspan='3'>";
$result .= anchor("$controller/insert/0", 'New entry');
$result .= "</td></tr>";
$result .= "<tr><td colspan='3'>";
$result .= anchor("$controller/read",
'Show all entries in the table');
$result .= "</td></tr>";
foreach ($query->result() as $row)
{
$result .= "<tr><td>";
$result .= $row->id;
$result .= " ";
$result .= $row->name;
$result .= "</td><td>";
$result .= anchor("$controller/insert/
$row->id",'Update this entry');
$result .= "</td><td>";
$result .= anchor("$controller/delete/
$row->id",'Delete');
$result .= "</td></tr>";
}
$result .= "</table>";
$data['text'] = $result;
$this->display->mainpage($data, $this->status);
}
else
{$place = __FILE__.__LINE__;
$outcome = "exception: $place:
no results from table $controller";
/*test block: were there results from this table/ controller?*/
if($test == 'yes')
{$place = __FILE__.__LINE__;
return $outcome;
}
/*end test block*/
else{
$message = "No data in the $controller table";
/*note: this specific exception must return to another controller which you know does contain data…… otherwise, it causes an infinite loop! */
$this->failure($message, 'sites');
}
}
}

/*queries the table to show all data, and formats it as an HTML table.*/
function read($controller)
{
$this->load->library('table');
$tmpl = array (
'table_open' => '<table border="1" cellpadding="4" cellspacing="0" width="100%">',
'row_alt_start' => '<tr bgcolor="grey">',
);
$this->table->set_template($tmpl);
$this->load->database();
$this->load->library('table');
$query = $this->db->get($controller);

$result = $this->table->generate($query);
$data['text'] = $result;
$this->display->mainpage($data);
}

/*DELETE FUNCTION: given table name and id number, deletes an entry*/
function delete($controller, $idno, $state='no', $test='no')
{
/*first check that the 'yes' flag is set. If not, go through the trydelete function to give them a chance to change their minds*/
if(!isset($state) || $state != 'yes')
{
/*test block: are 'yes' flags recognised?*/
if($test == 'yes')
{
$place = __FILE__.__LINE__;
$outcome = "exception at $place: sent state value $state to trydelete function ";
return $outcome;
}
else
/*end test block*/
{$this->trydelete($controller, $idno, 'no');}
}
else{
/*'yes' flag is set, so now make sure there is an id number*/
if(isset($idno) && $idno > 0 && is_int($idno))
/*test block: with this id no, am I going to do a delete?*/
{
if($test == 'yes')
{
$place = __FILE__.__LINE__;
$outcome = "OK at $place:
doing delete on id of $idno ";

return $outcome;
}
else{
/*end test block*/
/*if there is an id number, do the delete*/
$this->db->where('id', $idno);
$this->db->delete($controller);
$changes = $this->db->affected_rows();
}
if($changes != 1)
{
/*test block: did I actually do a delete? */
$place = __FILE__.__LINE__;
$outcome = "exception at $place: cdnt do delete op on $controller with id no of $idno";
if($test == 'yes')
{return $outcome;}
else
/*end test block*/
/*if there was no update, report it*/
{$this->failure($outcome);}
}
else{
/*test block: I did do a delete*/
if($test == 'yes')
{return 'OK';}
else{
/*end test block: report the delete*/
$this->showall($controller,
"Entry no. $idno deleted.");}
}
}
else
/*test block: report id number wasn't acceptable'*/
{
$place = __FILE__.__LINE__;
$outcome = "exception at: $place : id no of $idno set for delete op in $controller, expecting integer";
if($test == 'yes')
{return $outcome;}
else
/*endtest block: if I failed, report me*/
{$this->failure($outcome);}
}
}
}

/*TRYDELETE FUNCION: interrupts deletes with an 'are you sure? screen'*/
function trydelete($controller, $idno, $submit = 'no')
{
if($state == 'yes')
{$this->delete($controller, $idno, 'yes');}
else{
$result .= "<table><tr><td>Are you sure you want to delete this entry?</td></tr>";
$result .= form_open("$controller/delete");
$result .= form_hidden('id', $idno);
$result .= "<tr><td>";
$result .= form_submit('submit', 'yes');
$result .= "</td></tr>";
$result .= form_close();
$result .= "</table>";
$result .= anchor("$controller/showall",
"No, don't delete");
$data['text'] = $result;
$this->display->mainpage($data);
}
}

/*the most complex function. This creates an HTML form, based on the description of the fields in the form array. This is sent to our display model, which sets up a view and shows it to the user.
The view then sends a POST array back to the controller. The form can't call this model directly, so it has to call the controller, which refers it back to the model.
Note the function parameters:
1. The controller parameter is whichever controller/ table has called the model - eg the 'sites' controller, or the 'domains' controller. The controller has the same name as the table it manipulates.
2. The optional id parameter is the id of an individual entry in that table.
3. The optional 'test' parameter is so you can set the form up to make usable responses to self-test functions.
*/
function insert($controller='', $id=0, $test='no')
{
$myform = '';
$myid = 0;
$currentvalue = array();
/*test if the table exists*/
if(!$this->db->table_exists($controller))
{
$place = __FILE__.__LINE__;
$outcome = "exception: $place:looking for table $controller: it doesn't exist'";
if($test =='yes')
{
return $outcome;
}
else{
$this->failure($outcome, $controller);
}
}
else
{
if($test =='yes')
{
return 'OK';
}
}
/*end test block*/
/*next check if there is an id number. If there is, we need to get the values to populate the table fields*/
if(isset($id) && $id > 0)
{$myid = $id;
$this->db->where('id', $id);
$query = $this->db->get($controller);
if ($query->num_rows() > 0)
{
$row = $query->row();
//--------------work out the values we want!
foreach($row as $key =>$value)
/*
first of all work out what value you want to show as the existing value in each line of the form. In priority order these are:
1. the last value the user entered, from the post array
2. the value from the database
3. nothing, if neither of these is set.
if we got here, the id does exist and is returning values, so get the existing values into a value array. Or, if there is something in the validation array, use that instead*/
{
$_POST[$key] = $this->validation->$key;

if(isset($_POST[$key]))
{$currentvalue[$key] = $_POST[$key];}
else
{$currentvalue[$key] = $value;}
}
/*test block: there was an id number, so has the program gone for an update? if this is not a test, of course, just do the update*/
if($test == 'yes')
{
$place = __FILE__.__LINE__;
$outcome = "exception: $place: id of $id returned results from $controller table so have gone for update";
return $outcome;
}
/*end test block*/
$myform .= "<tr><td colspan='2'>Update existing entry number $id</td></tr>";
}
/*now catch situation where this query isn't returning results. We could only have got here with an integer set as our ID number, so
this probably means we are trying to delete an entry that doesn't
exist.*/
else{
$place = __FILE__.__LINE__;
$outcome = "exception: $place: despite id of $id cant get any results from $controller table";
if($test == 'yes')
/*test block: there was and ID but there were no results*/
{
return $outcome;
}
/*end test block*/
else
{$this->failure($outcome, $controller);}
}
}
/*there was no ID number, so this is a new entry*/
else{
/*If the user has filled in values, and has returned here because some of them didn't validate, we still need to repopulate the form with what he entered, so he only has to alter the one that didn't validate. Get these from the post array*/
if(isset($_POST))
{
foreach($_POST as $key => $value)

{
if(isset($_POST[$key]))
{$currentvalue[$key] = $_POST[$key];}
}
}
$myform .= "<tr><td colspan='2'>New entry</td></tr>";
/*test block: there was no ID, so this is a new entry*/
if($test == 'yes')
{
$place = __FILE__.__LINE__;
$outcome = "exception: $place: id of $id treated as no id, so going for new entry";
return $outcome;
}
/*end test block*/
}
/*the table exists, whether this is an update or new entry, so start to build the form*/
$myform .= "<table class='table'>";
$myform .= form_open("$controller/interim");
$myform .= '<p>This entry could not be made because...</P>';
$myform .= $this->validation->error_string;
/*the rest of this function is common to inserts or update.
Look up in the form array which form field type you want to display, and then build up the html for each different type, as well as inserting the values you want it to echo.*/
foreach($this->form[$controller] as $key => $value)
{
/*This switch statement develops several types of HTML form field based on information in the form array.
It doesn't yet cover checkboxes or radio or password fields. It adds a 'readonly' type, which is a field that only displays a value and doesn't let the user modify it*/
$fieldtype = $value[1];
$val_string = $this->validation->$key;
switch($value[1])
{
/*a simple input line*/
case 'input':
$data = array(
'name' => $key,

'id' => $key,
'value' => $currentvalue[$key],
'maxlength' => '100',
'size' => '50',
'style' => 'width:50%',
);
$myform .= "<tr><td>$value[0]</td><td>";
$myform .= form_input($data);
$myform .= "</td></tr>";
if($test == 'second')
{
return 'input';
}
break;
case 'textarea':
/*a text area field.*/
$data = array(
'name' => $key,
'id' => $key,
'value' => $currentvalue[$key],
'rows' => '6',
'cols' => '70',
'style' => 'width:50%',
);
$myform .= "<tr><td valign=
'top'>$value[0]</td><td>";
$myform .= form_textarea($data);
$myform .= "</td></tr>";
break;
case 'dropdown':
/*a drop-down box. Values are dynamically generated from whichever table was specified in the forms array. This table must have an id field (which is now entered in the form) and a name field (which is displayed in the drop-down box).*/
$dropbox = array();
if(isset($value[3]))
{
$temptable = $value[3];
$this->db->select('id, name');
$query = $this->db->get($temptable);
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$dropbox[$row->id] = $row->name;
}
}
}

$myform .= "<tr><td valign=
'top'>$value[0]</td><td>";
$myform .= form_dropdown($key, $dropbox, $currentvalue[$key]);
$myform .= "</td></tr>";
break;
case 'submit':
/*a submit field*/
$myform .= "<tr><td>$value[0]</td><td>";
$time = time();
$data = array(
'name' => 'submit',
'id' => 'submit',
);
$myform .= form_submit($data);
$myform .= "</td></tr>";
break;
case 'hidden':
/*generates a hidden field*/
$myform .= form_hidden($key, $currentvalue[$key]);
break;
case 'readonly':
/*generates a field the user can see, but not alter.*/
$myform .= "<tr><td>$value[0]</td><td>$currentvalue[$key]";
$myform .= form_hidden($key, $currentvalue[$key]);
$myform .= "</td></tr>";
break;
case 'timestamp':
/*generates a timestamp the first time it's set*/
// $myform .= "<tr><td>$value[0]</td><td>now()";
$timenow = time();
if($currentvalue[$key]==''||$currentvalue[$key]==0)
{$time = $timenow;}
else{$time = $currentvalue[$key];}
$myform .= form_hidden($key, $time);
$myform .= "</td></tr>";
break;
case 'updatestamp':
/*generates a timestamp each time it's altered or viewed*/
// $myform .= "<tr><td>$value[0]</td><td>now()";

$timenow = time();
$myform .= form_hidden($key, $timenow);
$myform .= "</td></tr>";
break;
default:
$place = __FILE__.__LINE__;
$outcome = "exception: $place:
switch can't handle $fieldtype";
/*test block: what if the switch doesn't recognise the form type?'*/
if($test == 'second')
{
return $outcome;
}
/*test block ends*/
else {
$this->failure($outcome, $controller);
}
}
/*end the foreach loop which generates the form*/
}
$myform .= form_hidden('submit',$time);
$myform .= form_close();
$myform .= "</table>";
/*Finally we've built our form and populated it! Now, stuff the form in an array variable and send it to the model which builds up the rest of the view.*/
$data['text'] = $myform;
$this->display->mainpage($data);
}

以上是关于PHP codeigniter标准crud模型的主要内容,如果未能解决你的问题,请参考以下文章

使用codeigniter的CRUD操作

要使用codeigniter框架还是标准的php? [关闭]

Codeigniter - 只能在 autoload.php 中加载模型

PHP 在CodeIgniter中将一个模型加载到另一个模型中

PHP Codeigniter模型

paypal 中的标准工作流程与 PHP codeigniter 集成