下面就是该程序整合到CI框架的代码:
Controller
project.php
<?php
class project extends CI_Controller{
function __construct()
{
parent::__construct();
$this->load->model('project_model');
}
public function index()
{
$this->load->view('project_view');
}
//保存数据的的方法
function save(){
//调用project_model中的save_project方法
$this->project_model->save_project($_POST['project_name']);
//获取插入的id
$id = mysql_insert_id();
$content = $_POST['context'];
//替换字符
$content = str_replace(".",".#",$content);
$content = str_replace("?","?#",$content);
$content = str_replace("!","!#",$content);
//分解内容
$str = explode("#",$content);
//获取总数
$count = count($str)-1;
$items = null;
for($i = 0 ; $i < $count ; $i++) {
$items .= "('{$str[$i]}',{$id})".',';
}
$items = rtrim($items,',');
$this->project_model->save_projectsentence($items);
$this->getdatas();
}
//显示数据
function getdatas(){
$list = $this->project_model->getdatas();
foreach($list->result_array() as $v){
$result[] = $v;
}
$data['list'] = $result;
$this->load->view('xianshi',$data);
}
}
?>
Model
project_model.php
<?php
//require_once 'common_model.php';
/**
* 增加上面类库返回结果集是以数组形式返回,原生态ci类库返回的结果集是object对象
*/
class project_model extends CI_Model{
function __construct(){
parent::__construct();
}
M
//向project表插入name字段方法
function save_project($project){
$sql="insert into project(name)VALUES('{$project}')";
return $this->db->query($sql);
}
//向project_sentences表插入sentence和id字段方法
function save_projectsentence($items){
$query = "insert into project_sentence (sentences,id)values{$items}";
return $this->db->query($query);
}
//显示name与sentence字段
function getdatas(){
$sql = "select p.name,ps.sentences from project p join project_sentence ps on p.id = ps.id";
// return $this->_query($sql);
return $this->db->query($sql);
}
}
?>
View
因为这里有两个网页,所以相对于CI,我们这里应有两个视图。分别是project_view(输入页面)和xianshi.php(显示页面)。
project_view
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>输入页面</title>
</head>
<body>VI
<form action="<?php echo site_url('project/save');?>" method="POST">
Project: <input type="text" name="project_name" />
<br>Context: <textarea name="context" rows="20" cols="80"></textarea>
<input type="submit">
</form>
</body>
</html>
xianshi.php
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>显示页面</title>
</head>
<body>
<div><a href="<?php echo site_url('project/index');?>">返回</a></div>
<table width="500" cellpadding="6" cellspacing="6" border="1">
<tr>
<th>Project_name</th>
<th>Sentences</th>
</tr>
<?php $name = null;
if(!empty($list)){
foreach($list as $v){
if($name != $v['name']){
$name = $v['name'];
?>
<tr>
<td align="center"><?php echo $v['name'];?></td>
<td align="center"><?php echo $v['sentences'];?></td>
</tr>
<?php }else{?>
<tr>
<td align="center"></td>
<td align="center"><?php echo $v['sentences'];?></td>
</tr>
<?php }}}?>
</table>
</body>
</html>
至此我们的代码就整合完了。转载自【函数式编程】https://www.imooc.com/article/33134