互联网程序设计·PHP语言之MySQL操作

互联网程序设计·PHP语言之MySQL操作

第1关 PHP对MySQL的基本操作

<?php
/**
 * 初始化数据库连接
 */

require 'public_function.php';
//创建对象,连接数据库
/*****begin*********/

$link=new mysqli('127.0.0.1','root', '123123');


/*****end*********/

//判断数据库连接是否成功,如果不成功则显示错误信息并终止脚本继续执行
if($link->connect_error){
    die('连接数据库失败!'.$link->connect_error);
}
//设置字符集,选择数据库
$link->query("drop database if exists 'educoder';");
$link->query("create database educoder;");
$link->query('set names utf8;');
$link->query('use educoder;');

//创建部门信息表
/*****begin*********/
$link->query("create table emp_dept (
  d_id int unsigned primary key auto_increment,
  d_name varchar(20) not null
)charset=utf8;");

/*****end*********/
//向部门信息表中插入数据
/*****begin*********/

$link->query("INSERT INTO emp_dept VALUES
(1, '开发部'), (2, '媒体部'), (3, '人事部'),(4, '后勤部'),
 (5, '市场部'),  (6, '运维部'), (7, '销售部')");




/*****end*********/

//修改用户表
/*****begin*********/

$link->query("ALTER TABLE user DROP d_name;
ALTER TABLE user ADD d_id int unsigned not null;");





/*****end*********/

//向其中添加用户数据
/*****begin*********/


$link->query("INSERT INTO emp_info VALUES
(1, '小红', 1, '2015-4-9 17:51:00', '2015-4-9 17:52:00'),

(2, '李四', 5, '2008-4-3 13:33:00', '2013-10-24 17:53:00'),

(3, '王五', 4, '2008-4-3 13:33:00', '2015-4-21 13:33:00'),

(4, '赵六', 4, '2008-4-3 13:33:00', '2015-3-20 17:54:00'),

(5, '小兰', 2, '1989-5-4 17:33:00', '2012-6-18 17:54:00'),

(6, '小新', 5, '1993-9-18 17:36:00', '2015-2-28 17:36:00'),

(7, '小白', 2, '1991-10-17 17:37:00', '2014-8-16 17:37:00'),

(8, '小智', 7, '1987-6-20 17:37:00', '2015-1-10 17:38:00'),

(9, '大头', 6, '1991-2-14 08:49:00', '2014-7-12 08:49:00'),

(10, '小明', 3, '1991-2-14 08:49:00', '2015-3-4 09:10:00'),

(11, '小刘', 1, '1992-3-18 14:52:00', '2014-7-21 09:00:00');");



/*****end*********/
//左连接查询
//填充下面sql语句
$sql="SELECT emp.e_id,emp.e_name,emp.date_of_birth,emp.date_of_entry,dept.d_name FROM emp_info emp LEFT JOIN emp_dept dept ON emp.d_id = dept.d_id";



$result=$link->query($sql);
$db=new Init();
$emp_info =$db->fetchAll($sql);
//设置常量,用以判断视图页面是否由此页面加载
define('APP', 'educoder');
//加载视图页面,显示数据
require 'list_html.php';

第2关 PHP实现下拉菜单显示数据 上

<?php
/**
 * 初始化数据库连接
 */



Class Init
{
    private $link;
    private static $host="127.0.0.1";
    private static $root="root";
    private static $password="123123";


    function __construct()
    {
        $this->link=new mysqli(self::$host,self::$root,self::$password);

        //判断数据库连接是否成功,如果不成功则显示错误信息并终止脚本继续执行
        if($this->link->connect_error){
            die('连接数据库失败!');
        }
        //设置字符集,选择数据库
        $this->link->query('set names utf8;');
        $this->link->query('use educoder;');
    }


    /**
     * 执行SQL的方法
     * @param string $sql 待执行的SQL
     * @return mixed 失败返回false,成功,如果是查询语句返回结果集,如果非查询类返回true
     */

    public function query($sql) {
       /***********Begin******/
        
       if ($result =$this->link->query($sql)) {
            return $result;
        }else{
            echo 'SQL执行失败:<br>';
            echo '错误的SQL为:',$sql,'<br>';
            echo '错误的代码为:',$this->link->connect_errno,'<br>';
            echo '错误的信息为:',$this->link->connect_error,'<br>';
            return false;
        }

        /*********end*******/
    }


    /**
     * 处理结果集中有多条数据的方法
     * @param string $sql 待执行的SQL
     * @return array 返回遍历结果集后的二维数组
     */
    public function fetchAll($sql) {

        if ($result =$this->link->query($sql)) {
            //执行成功
            //遍历结果集
           
        
          $rows=array();
        while($row=$result->fetch_assoc()){
            $rows[]=$row;
        }
        
        
        /*********end*******/
            //释放结果集资源
            $result->free();
            return $rows;

        } else {
            //执行失败
            return false;
        }
    }



    /**
     * 处理结果集中只有一条数据的方法
     * @param string $sql 待执行的SQL语句
     * @return array 返回结果集处理后的一维数组
     */
    public function fetchRow($sql) {
        //执行query()函数
        if ($result = $this->link->query($sql)) {
            //从结果集取得一次数据即可
           /***********Begin******/
        
        $row=$result->fetch_assoc();
        return $row;
        /*********end*******/
            
        } else {
            return false;
        }

    }

    /**
     * 对数据进行安全处理
     * @param string $data 待转义字符串
     * @return string 转义后的字符串
     */
    function safeHandle($data){
        //转义字符串中的HTML标签
        $data = htmlspecialchars($data);
        //转义字符串中的特殊字符
        $data = mysqli_real_escape_string($this->link,$data);
        return $data;
    }

}



//初始化数据库
$db=new Init();

//判断是否有表单提交
if(!empty($_POST)){

    //声明变量$value,用来保存字段信息
    $fields = array('e_name','e_dept','date_of_birth','date_of_entry');

    //声明变量$value,用来保存值信息
    $value = array();

    //遍历$allow_field,获取输入员工数据的键和值
    foreach($fields as $k => $v){

        $data = isset($_POST[$v]) ? $_POST[$v] : '';

        if($data=='') die($v.'字段不能为空');

        $data =$db-> safeHandle($data);

        //把字段使用反引号包裹,赋值给$fields数组
        $fields[$k] = "`$v`";

        //把值使用单引号包裹,赋值给$values数组
        $values[] = "'$data'";
    }

    //将$fields数组以逗号连接,赋值给$fields,组成insert语句中的字段部分
    $fields = implode(',', $fields);

    //将$values数组以逗号连接,赋值给$values,组成insert语句中的值部分
    $values = implode(',', $values);

    //最后把$fields和$values拼接到insert语句中,注意要指定表名
    $sql = "insert into `emp_info` ($fields) values ($values)";

    //执行SQL
    if($res = $db->query($sql)){
        //成功时返回到 showList.php
        header('Location: ./showList.php');
        //停止脚本
        die;
    }else{
        //执行失败
        die('员工添加失败!');
    }
}
$sql = 'select * from emp_dept';
//调用fetchAll()函数,执行SQL并进行数据处理,把处理后的部门数据赋值给$emp_dept
$emp_dept = $db->fetchAll($sql);

//没有表单提交时,显示员工添加页面
define('APP', 'educoder');
require 'add_html.php';

第3关 PHP实现下拉菜单显示数据 下

<?php
require "empUpdate.php";
if(!defined('APP')) die('error!');
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>员工信息编辑</title>
    <link rel="stylesheet" href="./js/jquery.datetimepicker.css"/ >
    <script src="./js/jquery.js"></script>
    <script src="./js/jquery.datetimepicker.js"></script>
    <script>
        $(function(){
            $('#date_of_birth').datetimepicker({lang:'ch'});
            $('#date_of_entry').datetimepicker({lang:'ch'});
        });
    </script>
    <style>
        body{background-color:#eee;margin:0;padding:0;}
        .box{width:400px;margin:15px auto;padding:20px;border:1px solid #ccc;background-color:#fff;}
        .box h1{font-size:20px;text-align:center;}
        .profile-table{margin:0 auto;}
        .profile-table th{font-weight:normal;text-align:right;}
        .profile-table input[type="text"]{width:180px;border:1px solid #ccc;height:22px;padding-left:4px;}
        .profile-table .button{background-color:#0099ff;border:1px solid #0099ff;color:#fff;width:80px;height:25px;margin:0 5px;cursor:pointer;}
        .profile-table .td-btn{text-align:center;padding-top:10px;}
        .profile-table th,.profile-table td{padding-bottom:10px;}
        .profile-table td{font-size:14px;}
        .profile-table .txttop{vertical-align:top;}
        .profile-table select{border:1px solid #ccc;min-width:80px;height:25px;}
        .profile-table .description{font-size:13px;width:250px;height:60px;border:1px solid #ccc;}
    </style>
</head>
<body>
<div class="box">
    <h1>修改员工信息</h1>
    <form method="post">
        <table class="profile-table">
            <tr><th>姓名:</th><td><input type="text" name="e_name" value="<?php echo $emp_info['e_name']; ?>"/></td></tr>
            <tr><th>所属部门:</th>
                <td>
                    <!—下拉菜单开始-->
                    <!—在输出每个部门信息时,判断是否为该员工当前所属部门,如果是设置为默认项selected='selected'-->
 					<!somecodes here-->
                    <select name="d_id">
                    <?php foreach ($emp_dept as $row){?>
                    <option value="<?php echo $row['d_id'];?>"><?php echo $row['d_name'];?></option>
                    <?php }?>
                    </select>
                    <!—下拉菜单结束-->
                </td></tr>
            <tr><th>出生年月:</th><td><input id="date_of_birth" name="date_of_birth" type="text" value="<?php echo $emp_info['date_of_birth']; ?>"></td></tr>
            <tr><th>入职日期:</th><td><input id="date_of_entry" name="date_of_entry" type="text" value="<?php echo $emp_info['date_of_entry']; ?>"></td></tr>
            <tr><td colspan="2" class="td-btn">
                    <input type="submit" value="保存资料" class="button" />
                    <input type="reset" value="重新填写" class="button" />
                </td></tr>
        </table>
    </form>
</div>
</body>
</html><?php
require "empUpdate.php";
if(!defined('APP')) die('error!');
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>员工信息编辑</title>
    <link rel="stylesheet" href="./js/jquery.datetimepicker.css"/ >
    <script src="./js/jquery.js"></script>
    <script src="./js/jquery.datetimepicker.js"></script>
    <script>
        $(function(){
            $('#date_of_birth').datetimepicker({lang:'ch'});
            $('#date_of_entry').datetimepicker({lang:'ch'});
        });
    </script>
    <style>
        body{background-color:#eee;margin:0;padding:0;}
        .box{width:400px;margin:15px auto;padding:20px;border:1px solid #ccc;background-color:#fff;}
        .box h1{font-size:20px;text-align:center;}
        .profile-table{margin:0 auto;}
        .profile-table th{font-weight:normal;text-align:right;}
        .profile-table input[type="text"]{width:180px;border:1px solid #ccc;height:22px;padding-left:4px;}
        .profile-table .button{background-color:#0099ff;border:1px solid #0099ff;color:#fff;width:80px;height:25px;margin:0 5px;cursor:pointer;}
        .profile-table .td-btn{text-align:center;padding-top:10px;}
        .profile-table th,.profile-table td{padding-bottom:10px;}
        .profile-table td{font-size:14px;}
        .profile-table .txttop{vertical-align:top;}
        .profile-table select{border:1px solid #ccc;min-width:80px;height:25px;}
        .profile-table .description{font-size:13px;width:250px;height:60px;border:1px solid #ccc;}
    </style>
</head>
<body>
<div class="box">
    <h1>修改员工信息</h1>
    <form method="post">
        <table class="profile-table">
            <tr><th>姓名:</th><td><input type="text" name="e_name" value="<?php echo $emp_info['e_name']; ?>"/></td></tr>
            <tr><th>所属部门:</th>
                <td>
                    <!—下拉菜单开始-->
                    <!—在输出每个部门信息时,判断是否为该员工当前所属部门,如果是设置为默认项selected='selected'-->
 					<!somecodes here-->
                    <select name="d_id">
                    <?php foreach ($emp_dept as $row){?>
                    <option value="<?php echo $row['d_id'];?>"><?php echo $row['d_name'];?></option>
                    <?php }?>
                    </select>
                    <!—下拉菜单结束-->
                </td></tr>
            <tr><th>出生年月:</th><td><input id="date_of_birth" name="date_of_birth" type="text" value="<?php echo $emp_info['date_of_birth']; ?>"></td></tr>
            <tr><th>入职日期:</th><td><input id="date_of_entry" name="date_of_entry" type="text" value="<?php echo $emp_info['date_of_entry']; ?>"></td></tr>
            <tr><td colspan="2" class="td-btn">
                    <input type="submit" value="保存资料" class="button" />
                    <input type="reset" value="重新填写" class="button" />
                </td></tr>
        </table>
    </form>
</div>
</body>
</html>

第4关 PHP实现分页显示数据

<?php
/**
 * 分页链接生成函数
 * $page  URL传递的page值
 * $max_page  最大页码值
 * $show_page_num 页面中显示多少页码
 */
function makePageHtml($page, $max_page, $show_page_num = 5) {


    //将首页的链接存入字符串$page_html中
    /*******Begin********/
    $page_html='<a href="?page=1">首页</a>&nbsp;';
    
    /*******end*********/

    //根据当前页码$page计算出它的所在分组,以及需要显示的第一页$i和最后一页$max_i
     /*******Begin********/
   $page_grep=ceil($page/$show_page_num);
   $i=$show_page_num*($page_grep-1)+1;
   $max=$page_grep*$show_page_num;
   $max_i=($max<=$max_page)?$max:$max_page;
    
    /*******end*********/

    for ($i; $i <= $max_i; $i++) {
        //判断是否有上一个页面分组,若有则向$page_html中添加"<"的链接
      /*******Begin********/
  if(($i+$show_page_num-1) % $show_page_num==0 && $i>1){
      $page_html .='<a href="?page=' . ($i-1) . '"&lt;</a>&nbsp;';
  }
    
    /*******end*********/

        //判断是否为当前选中页,并添加入$page_html。这是因为当前选择页的链接与其他页的链接不同
      /*******Begin********/
    if($i==$page){
        $page_html .='<a class = "curl" href="?page=' . $i . '">' . $i . '</a>&nbsp;';
    }else{
        $page_html .='<a href="?page=' . $i . '">' . $i . '</a>&nbsp;';
    }
    
    /*******end*********/

        //判断是否有下一页,若有则向$page_html中添加">"的链接
    /*******Begin********/
   if($i % $show_page_num==0 && $i < $max_page){
       $page_html .='<a href="?page=' . ($i+1) . '">&gt;</a>&nbsp;';
   }
    
    /*******end*********/


    }
    //将尾页的链接存入字符串$page_html中
    /*******Begin********/
   $page_html .='<a href="?page=' . $max_page . '">尾页</a>&nbsp;';
  
    /*******end*********/
    //返回显示分页链接的字符串
    return $page_html;
}
require "showList.php";
587 Views
分享你的喜爱
linwute
linwute

我要像梦一样自由,像大地一样宽容;
在艰辛放逐的路上,点亮生命的光芒;
我要像梦一样自由,像天空一样坚强;
在曲折蜿蜒的路上,体验生命的意义;

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注