陈力:传智播客古代 珍宝币 泡泡龙游戏开发第38讲:PHP数据库编程mysql

陈力:传智播客古代 珍宝币 泡泡龙游戏开发第38讲:PHP数据库编程mysql

      php程序设计语言为我们提供了mysql扩展库、mysqli扩展库、Pdo三种方式来操作mysql数据库。本文为贵阳网站建设的朋友介绍mysql_connect()链接数据库,通过mysql_select_db(“数据库名”[,$conn]);选择数据库和mysql_query($sql)进行查询,之后用mysql_fetch_row($res)取得数据,最后介绍了Mysql的增删改查等操作。

一、mysql数据库
    Php程序设计语言有三种方式来操作我们的mysql数据库:mysql扩展库、mysqli扩展库、Pdo。
mysql扩展库和mysql数据库的区别:mysql数据库是用于存放数据。mysql扩展库是一堆函数,是PHP设计者提供给程序员用于完成对mysql数据库的各种操作(CRUD)。
    mysql数据库的三层结构示意图:

软件设计,贵阳网站建设,PHP教程

二、使用php的mysql扩展库完成对mysql操作
    编写一个程序,这个程序从user1表中读取数据,并打印在网页中。
(1)搭建实验环境:
    启用mysql扩展库:在php.ini文件中去配置mysql扩展库:extension=php_mysql.dll。
可以通过 <?php phpinfo() ?> 可以查看当前php支持什么扩展库。
(2)在mysql数据库中创建一个库,并创建user1表和插入表的数据。
    创建一张用户表,供我们使用:
create table user1(
id int primary key auto_increment,
name varchar(32) not null,
password varchar(64) not null,
email varchar(128) not null,
age tinyint unsigned not null
)
(3)预先加入数据
insert into user1 (name,password,email,age) values ('zs',md5('123456'),'zs@sohu.com',30);
insert into user1 (name,password,email,age) values ('ls',md5('123456'),'ls@sohu.com',40);
insert into user1 (name,password,email,age) values ('ww',md5('123456'),'ww@sohu.com',50);
insert into user1 (name,password,email,age) values ('郭天',md5('123456'),guotian@sohu.com',50);
(4)新建一个php工程。编写程序,建立连接($conn)
$conn=mysql_connect(“主机名”,”用户名”,”密码”);
(5)选择数据库,设置字符集,并发送sql
mysql_select_db(“数据库名”[,$conn]);
mysql_query(“set names utf8”,$conn);
$res = mysql_query($sql); 
(6)从代表结果集的$res中取出数据,输出到页面。
(7)断开与数据库的连接$conn,并释放相关资源$res。
     编写一个程序,这个程序从user1表中读取数据,并打印在网页中。
<?php
 //mysql扩展库操作mysql数据库步骤如下
 $conn=mysql_connect("127.0.0.1","root","root");//1. 获取连接
 if(!$conn){
  die("连接失败".mysql_error());
 }
 mysql_select_db("test");//2. 选择数据库
 mysql_query(“set names utf8”); //3. 设置操作编码,保证我们的php程序是按照utf8码操作。
 //4. 发送指令sql (ddl 数据定义语句, dml(数据操作语言 update insert ,delete) ,dql (select ), dtl 数据事务语句 rollback commit... )
 $sql="select * from user1";
 //$res 表示结果集,你可以简单的理解就是 一张表。
 $res=mysql_query($sql,$conn);
 //var_dump($res); //mysql result 资源类型
 //5. 接收返回的结果,并处理.(显示)
 // mysql_fecth_row 会依次取出$res结果集的下一行数据,赋值给$row
 // $row就是一个数组, 样式array(5) { [0]=> string(1) "1" [1]=> string(2) "zs" [2]=> string(32) "e10adc3949ba59abbe56e057f20f883e" [3]=> string(11) "zs@sohu.com" [4]=> string(2) "30" } 
 mysql_close($conn);
 while($row=mysql_fetch_row($res)){
  //第一种取法是 同 $row[$i]
  //echo "<br/> $row[0]--$row[1]--$row[2]";
  //echo "<br/>";
  //var_dump($row);
  //第二种取法
  foreach($row as $key => $val){
   echo "--$val";
  }
  echo "<br/>";
 }
 mysql_free_result($res); //6. 释放资源,关闭连接
 //mysql_close($conn); //这句话可以没有,建议有。
?>

    如果执行的是dml语句,则返回bool。如果执行的是dql语句,则返回查询结果mysql result。
    程序中的$res用于代表Sql语句的执行结果,使用完 $res 结果集后,一定要及时的释放资源。mysql_close() 如果没有的话,系统也会自动的关闭。从$res获取行数据的时候,处理 mysql_fetch_row($res),还有三个方法:
mysql_fetch_row($res) ,返回一个索引的数组(推荐)。
mysql_fetch_assoc($res),返回一个关联数组。
mysql_fetch_array($res) ,返回索引数组和关联数组(两套)。
mysql_fetch_object($res) ,把一行数据当做一个对象返回。

    通过var_dump($res) 我们可以更加清楚的知道,当执行查询的时候,mysql_query() 返回 mysql result 类型,执行dml语句返回bool类型!!!
    取出数据结果集有四种方式(mysql_fetch_row,,mysql_fetch_assoc, mysql_fetch_array, ,mysql_fetch_object) 区别?如何选择使用问题。
    区别:前两个效率相当: mysql_fetch_row从结果集中取得一行作为索引数组 mysql_fetch_assoc 取出关联数组(需要通过列名来取数据)。
    第三个效率偏低: 因为 mysql_fetch_array从结果集中取得一行作为关联数组和数字数组二者兼有,因此代价高,不推荐使用可用通过print_r 或者 var_dump来测试。
    第四个一般我们不用:因为我们往往自定义对象来处理: mysql_fetch_object 从结果集中取得一行作为对象。
    取出结果集中的数据 除了该ppt列举出的案例外:还可以使用如下方法:
while(list($id,$name,$passwd)=mysql_fetch_row($result)){  //这里不能使用mysql_fetch_assoc().必须包含索引数组才可以
 echo $id.$name,$passwd;
}
while($row=mysql_fetch_row($result)){  //这里能使用mysql_fetch_assoc(),或者mysql_fetch_array()
 foreach($row as $val){
  echo $val.”-”;
 }
}

    程序运行完后,要释放程序在运行过程中,创建的那些与数据库进行交互的资源,这些对象通常是$result, 和连接数据库的资源$conn。
    特别是$conn,它是非常稀有的资源,用完后要及时释放,如果$conn不能及时、正确的关闭,极易导致系统宕机。$conn的使用原则是尽量晚创建,尽量早的释放。
    尽管我们可能会看到mysql_close()函数有这样一句话:
    通常不需要使用 mysql_close(),因为已打开的非持久连接会在脚本执行完毕后自动关闭。参见释放资源。但是仍建议大家及时关闭资源,尽快释放。

三、对mysql数据库进行CRUD
    mysql_query用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个函数向数据库发送增删改查语句即可。
    演示通过mysql扩展库,进行dml操作。
    代码:
<?php
 //演示对user1表进行增,删除,修改的操作。
 $conn=mysql_connect("localhost","root","root");
 if(!$conn){
  die("出错了".mysql_error());
 }
 mysql_select_db("test",$conn) or die(mysql_error());
 mysql_query("set names utf8");
 //$sql="insert into user1 (name,password,email,age) values('小明',md5('123'),'xiaoming@sohu.com',34)";
 //$sql="delete from user1 where id=5";
 $sql="update user1 set age=100 where id=6";
 //如果是dml操作,则返回bool
 $res=mysql_query($sql,$conn);
 if(!$res){
  die("操作失败".mysql_error());
 }
 //看看有几条数据
 if(mysql_affected_rows($conn)>0){//当删除的ID号不存在时,返回OK,但影响条数为0
  echo "操作成功";
 }else{
  echo "没有影响到行数";
 }
 mysql_close($conn);
?>

四、封装工具类SqlTool
     从上面的两个文件看出,代码的复用性和可维护性不高,PHP编程中,通常是将对数据库的操作,封装成一个工具类SqlTool。
<?php
 class SqlTool {
  private $conn;
  private $host="localhost";
  private $user="root";
  private $password="root";
  private $db="test";
  function SqlTool(){
  $this->conn=mysql_connect($this->host,$this->user,$this->password);
   if(!$this->conn){
    die("连接数据库失败".mysql_error());
   }
   mysql_select_db($this->db,$this->conn);
   mysql_query("set names utf8");
  }
  // 完成select
  public  function execute_dql($sql){
   $res=mysql_query($sql,$this->conn) or die(mysql_error());
   return $res;
  }
  //完成 update,delete ,insert
  public  function execute_dml($sql){
   $b=mysql_query($sql,$this->conn);
   //echo "添加的id=".mysql_insert_id($this->conn);
   if(!$b){
    return 0;//失败
   }else{
    if(mysql_affected_rows($this->conn)>0){
     return 1;//表示成功
    }else{
     return 2;//表示没有行数影响.
    }
   }
  }
 }
?>
测试:
<?php
 require_once "SqlTool.class.php";
 $sql="insert into user1 (name,password,email,age) values('小明',md5('123'),'xiaoming@sohu.com',34)";
 //$sql="drop database hsp";
 $sqlTool=new SqlTool();
 $res=$sqlTool->execute_dml($sql);
 if($res==0){
  echo "失败";
 }else if($res==1){
  echo "成功";
 }else if($res==2){
  echo "没有行数影响";
 }
//****************************dql*******************
 $sql="select * from user1";
 $sqlTool=new SqlTool();
 $res=$sqlTool->execute_dql($sql);
 while($row=mysql_fetch_row($res)){
  foreach($row as $key=>$val){
   echo "--$val";
  }
  echo "<br/>";
 }
 mysql_free_result($res);*/
?>
    mysql扩展库还有很多其它的函数,我们一起来看看,请注意有些函数并不常用,我们前面讲的mysql扩展库函数几乎可以满足所有项目开发的需求,所以大家了解一下即可。

五、通过表名显示记录信息
     请编写一个函数,可以接受一个表名,然后把表的头和记录显示在网页。
<?php
 function show_tab_info($table_name){
  $conn=mysql_connect("localhost","root","root");
  if(!$conn){
   die("连接失败".mysql_error());
  }
  echo "hello";
  mysql_select_db("test",$conn);
  mysql_query("set names utf8");
  //$sql="select * from $table_name";
  $sql="desc $table_name";
  $res=mysql_query($sql,$conn);
  //我要知道总有多少行,和多少列
  $rows=mysql_affected_rows($conn);
  $colums=mysql_num_fields($res);
  echo "$rows=$colums";
  echo "<table border=1><tr>";
  //表头
  for($i=0;$i<$colums;$i++){
   $field_name=mysql_field_name($res,$i);
   echo "<th>$field_name</th>";
  }
  echo "</tr>";
  while($row=mysql_fetch_row($res)){
   echo "<tr>";
   for($i=0;$i<$colums;$i++){
    echo "<td>$row[$i]</td>";
   }
   echo "</tr>";
  }
  echo "</table>";
 /* while($field_info=mysql_fetch_field($res)){
   echo  "<br/>".$field_info->name;
  }*/
  //var_dump($field_info);
 }
 show_tab_info("user1");
?>


六、在线词典的案例
mainView.php源代码
<html>
<head>
<title>在线词典</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
</head>
<img src="ciba.png" />
<h1>查询英文</h1>
<form action="wordProcess.php" method="post">
请输入英文:<input type="text" name="enword"/>
<input type="hidden" value="search1" name="type"/>
<input type="submit" value="查询"/>
</form>
<h1>查询中文</h1>
<form action="wordProcess.php" method="post">
请输入中文:<input type="text" name="chword"/>
<input type="hidden" value="search2" name="type"/>
<input type="submit" value="查询"/>
</form>
</html>

wordProcess.php源代码
<?php
 require_once 'SqlTool.class.php';
 header("Content-type: text/html;charset=utf-8");
 //接收type
 if(isset($_POST['type'])){
  
  $type=$_POST['type'];
 }else {
  echo "输入为空";
  echo "<a href='mainView.php'>返回重新查询</a>";
 }
 if($type=="search1"){
  
   //接收英文单词
   if(isset($_POST['enword'])){
    $en_word=$_POST['enword'];
   }else{
    echo "输入为空";
    echo "<a href='mainView.php'>返回重新查询</a>";
   }
   
   //看看数据库中有没有这条记录
   //用什么,查询什么
   $sql="select chword from words where enword='".$en_word."' limit 0,1";
   //设计表.
   //查询.(面向对象)
   $sqlTool = new SqlTool();
   $res=$sqlTool->execute_dql($sql);
   if($row=mysql_fetch_assoc($res)){
    
    echo $en_word."对应的中文意思是--".$row['chword'];
    echo "<br/><a href='mainView.php'>返回重新查询</a>";
   }else{
    echo "查询没有这个词条";
    echo "<br/><a href='mainView.php'>返回重新查询</a>";
   }
   mysql_free_result($res);
 }else if($type=="search2"){
   //接收中文单词
   if(isset($_POST['chword'])){
    $ch_word=$_POST['chword'];
   }else{
    echo "输入为空";
    echo "<a href='mainView.php'>返回重新查询</a>";
   }
   
   //看看数据库中有没有这条记录
   //用什么,查询什么
   $sql="select enword from words where chword like '%".$ch_word."%'";
   //设计表.
   //查询.(面向对象)
   $sqlTool = new SqlTool();
   $res=$sqlTool->execute_dql($sql);
   //查询有东西
   if(mysql_num_rows($res)>0){ 
    while($row=mysql_fetch_assoc($res)){
     echo "<br/>".$ch_word."对应的英文意思是--".$row['enword'];
    }
   }else{
    echo "查询没有这个词条";
   }
   echo "<br/><a href='mainView.php'>返回重新查询</a>";
   mysql_free_result($res);
 }
?>


SqlTool.class.php源代码
<?php
 class SqlTool {
  //属性
  private $conn;
  private $host="localhost";
  private $user="root";
  private $password="root";
  private $db="worddb";
  function SqlTool(){
   $this->conn=mysql_connect($this->host,$this->user,$this->password);
   if(!$this->conn){
    die("连接数据库失败".mysql_error());
   }
   mysql_select_db($this->db,$this->conn);
   mysql_query("set names utf8");
  }
  //方法..
  // 完成select dql
  public  function execute_dql($sql){
   $res=mysql_query($sql,$this->conn) or die(mysql_error());
   return $res;
  }
  //完成 update,delete ,insert dml
  public  function execute_dml($sql){
   $b=mysql_query($sql,$this->conn);
   //echo "添加的id=".mysql_insert_id($this->conn);
   if(!$b){
    return 0;//失败
   }else{
    if(mysql_affected_rows($this->conn)>0){
     return 1;//表示成功
    }else{
     return 2;//表示没有行数影响.
    }
   }
  }
 }
?>

【推荐阅读】陈力:传智播客古代 珍宝币 泡泡龙游戏开发第38讲:PHP数据库编程mysql

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值