php操作数据库的三种方法
1.mysql扩展库   (最早的);2.mysqli扩展库;3.pdo

php 数据类型
1.基本数据类型;2.符合数据类型;3.特殊数据类型 null 和资源数据类型

mysql扩展库和mysql数据库的区别
1.mysql扩展库包含操作mysql数据库的函数(CRUD)
2.数据库三层结构:sql指令(来自客户端或者服务器)-->dbms(二次编译成二进制命令)-->操作数据库

1.环境搭建
1.1.启用mysql扩展库
php.ini ---extension =php_mysql.dll
可以通过 <?php phpinfo();?> 查看使用了那些扩展库
create table users{         //  大写执行效率高,不过无所谓
id int  primary key auto_increment,  //unsigned 无符号,范围大一倍
name varchar(32) not null,  //char varchar的区别
password varchar(64) not null,  //空间按32的倍数来给,标准习惯
email varchar(128) not null,
age tinyint unsigned not null
}

insert into users(name,password,email,age) values('zs',md5('123456'),'123@163.com',30);
insert into users(name,password,email,age) values('伟',md5('123456'),'123@163.com',30);
题外话:md5,不可逆

php代码

//1.获取连接
$conn =mysql_connect("127.0.0.1","root","root");
if(!$conn){
die("连接表".mysql_error());
}
//2.选择数据库
mysql_select_db("test");
//3.设置操作编码(建议有)
mysql_query("set names utf8")
//4.sql指令(ddl数据定义语句,dml数据操作语句(增,改删),dql数据查询语句(查),dtl数据管理语句 rollback commit)
$sql="select * from users";
$res =mysql_query($sql,$conn); //指定$conn,执行效率高
//var_dump($res);               //mysql result 资源类型
//5.接受结果,处理
while($row=mysql_fetch_row($res)){  //取出下一行
//第一种取法
 echo"<br/>".row[0]."--".row[1];
//第二种取法
foreach($row as $key=>$val)
{
echo"--$val";
}
echo"<bt/>";
}
//6.释放资源,关闭连接
mysql_free_result($res);
mysql_close($conn);   //通常不需要写,反正不会及时关闭,而且有系统关闭
题外话:cmd命令 netstat -an    //查看当前的网络连接

mysql_query($sql,$conn);返回的结果类型
1. dql --- 返回数据库资源
2.dml---返回bool
mysql_fetch_row($res);    返回索引数组 效率最高
mysql_fetch_assoc($res);  返回关联数组
mysql_fetch_array($res);  返回索引数组和关联数组
mysql_fetch_object($res);  把一行数据,当做一个对象  $row->email;

mysql command client 的使用

MySql Command Line Client mysql数据库客户端-- 使用方法
密码--回车
show databases;--回车
use test; --回车
show tables; -- 回车    //查看表结构和所在数据库
\s     //查看当前表所在数据库
drop table users;
show variables like '%char%';   //不能插入中文数据
set character_set_client=gbk;   //该客户端的编码识别问题
set character_set_results=gbk;
或者使用
set names gbk;    //取代上面两行

mysql扩展库其他操作函数

public function show_table($table_name){

$sql="select * from $table_name";  //"des $table_name";
require_once("sqlhelper.class.php");
$sqlhelper =new sqlhelper();
$res =$sqlhelper->Execute_dql($sql);
echo"<table border=1><tr>";
$rowcount =mysql_affected_rows($conn);
$fieldcount=mysql_num_fields($res);

for($i =0;$i<$fieldcount;$i++){
$field_name=mysql_field_name($res,$i);
echo"<th>$field_name</th>";
}
echo"</tr></table>";

while($row =mysql_fetch_row($res))
echo"</tr>";
for($i=0;$i<$fieldcount;$i++){
echo"<td>$row[$i]</td>";
}
echo"<tr>";
/*//循环获取列名
while(mysql_fetch_field($res)){
echo"<th>".$field_name.</th>;
}
*/
}

mysql扩展库--sqlhelper创建

mysql_query($sql,$conn);返回的结果类型
1. dql --- 返回数据库资源
2.dml---返回bool
if(!$res){
die("operate fail".mysql_error());
}
if(mysql_affected_rows($conn)>0){
echo" operate success";
}
else{
echo"no affected row";
}

创建sqlhelper.class.php  类

public class sqlhelper
{private $host="localhost";private $username="root";private $password ="root";private $db="test";public function sqlhelper(){$conn=mysql_connect($host,$username,$password);if(!$conn){die("connect fail".mysql_error());}mysql_select_db($this->db,$this->conn) or die(mysql_error());mysql_query("set names utf8");}public function Execute_dql($sql){$res=mysql_query($sql,$this->conn);return $res;}mysql_free_result($res);mysql_close($this->conn) or die(mysql_error());
}public function Execute_dml($sql){$res=mysql_query($sql,$this->conn);if(!$res){return 0;  //失败
        }else{if(mysql_affected_rows($this->conn)>0){return 1;}else{return 2;}}    }

调用sqlhelper使用
$sql="select * from users";
$exe_table =new mysql();
$res =$exe_table->execute_dql($sql);
while($row =mysql_fetch_row($res)){
   foreach($row as $key=>$value){
   echo $value;
}
   echo"<br/>"
}
mysql_free_result($res);

$sql="delete from users";
$exe_table =new mysql();
$exe_table->execute_dml($sql);

mysql扩展库---字典查询示例

查询示例中sql语句的优化
mysql limit 0,1  指令
select *   //开销较大
while 单查开销比 if 大一点

<?phprequire_once'SqlHelper.class.php';if(isset($_REQUEST['Enname'])){
$en_word=$_REQUEST['Ename'];
}else{
echo"input null";
echo"<a href='mainView.php'>return</a>"
}$sql="select chword from words where enword='".$en_word."'limit 0,1";///
$sql="select enword from words where chword like '%".$en_word."%' limit 0,1";
if(mysql_num_rows($res)){
while($row=mysql_fetch_assoc($res)){
}else{
}
mysql_free_result($res);
mysql_close($conn);
}
?>

中查英,英查中各一个form,用hidden的值来区分,在同一处理页里进行处理。

mysqli 特性,sqlhelper封装类

1.mysql扩展库和mysqli扩展库的区别
  1.1.mysql---面向过程编程
  mysqli---面向对象编程(主流)同时提供面向过程编程(过渡)
  (语法上的特征:mysqli将mysql中使用的参数封装成相应的对象)
  1.2.mysqli更安全更高效。
2.

<?php
header("Content_type:text/html;charset=utf-8")
public class SqlHelper
{private static $host="localhost";private static $username="root";private static $password="root";private static $db="test";private mysqli="";public __construct{//self::$host$this->mysqli=new MySQLi(self::$host,self::$username,self::$password,self::$db)   //MySQLi中大小无所谓if(!$this->mysqli->conncet_error){die("connect error".$this->mysqli->connect_error);}}public Execute_dql($sql){//des select show explain 返回mysqli result$res=$this->mysqli->query($sql) or die("Query error".$this->mysqli->error);if($res)while($row=$res->fetch-assoic()){foreach($row as $key=>$value)echo"$value";}echo"<br/>";
//$res->free();资源的释放应该在调用后释放
//$this->mysqli->close();
}public Execute_dml($sql){$res=$this->mysqli->query($sql) die("Query error".$this->mysqli->error);;if($res){$counts=$this->mysqli->affeced_rows();if($counts>0){//echo"affected rows".$counts;return 0 ;           }else{//echo"no rows affected"return 1;           }}else{return 2;           //echo"opreate fail";
        }$this->mysqli->close();
}public Execute_Batch_dql($sql){//批量查询$res=$this->mysqli->multi_query($sql);if(!$res){echo"operate error".$this->mysqli->error;}else{do{$result=$res->store_result(); //每执行一次取出一个结果集while($row =$result->fetch_row()){foreach($row as $key=>$val){echo"--$val";}echo"</br>";}$result->free();if(!$res->more_results()){break;}}while($res->next_result();)}$this->mysqli->close();
}//批量dmlpublic Execute_Batch_dml($sql){$res=$this->mysqli->multi_query($sql);   //批量执行,返回true,false。if(!$res){echo"operate error".$this->mysqli->error;}else{}$this->mysqli->close();}
}
?>                                                        

mysqli面向过程编程

<?php$mysqli=mysqli_connect("localhost","root","root","db") or die("conncet error".mysqli_connect_error($mysqli));mysqli_query(set names utf8);$sql="select * from users";$res =mysqli_query($mysqli,$sql);if(!$res){echo"operate error".mysqli_error($mysqli);}else{while(mysqli_fetch_row($res)){foreach($row as $key=>$value){echo"--$value";}echo"</br>";}mysqli_free_result($res);mysqli_close($mysqli);
}
?>            

mysqli--批量dql,dml,事务,预处理

批量dql,dml的好处---提高性能速度。
1.批量执行中dml最好不要和dql一起使用,可能会不稳定。
2.批量执行sql语句的不同操作必须用;隔开。

2.sql语句中如果字段为string类型,必须加'';
  如果字段为数字类型,可以加'',也可以不加'';

<?php
requrie_once"SqlHelper.class.php";
$sql="update test set name ='cao'where id=1;";
$sql.="delete from test where id>1;";
$sql.="insert into test (name,age,score) values('piliang',10,100)"$mysqli=new SqlHelper();
$mysqli->Execute_Batch_dml($sql);
?>

3.事务的应用---转账(dml)

1.acid  原子性,一致性,隔离性,持久性。
  2.事务的sql操作
    2.1. start transcation;
    2.2. savepoint a;
    2.3. sql操作;
    2.4. rollback to a;或者 commit;
  3.一旦执行commit就无法再rollback。(持久性)
  4.事务的php操作

  <?phprequire_once("SqlHelper.class.php");$mysqli =new SqlHelper();$mysqli->autocommit(false);$dml1=$mysqli->query("update user set age=age-2  where id=1");$dml2=$mysqli->query("update user set age=age+2  where id=2");if(!$dml1||!$dml2)  {$mysqli->rollback();}  else  {$mysqli->commit();}$mysqli->close();
?>

4.预处理
从数据库请求资源时,造成性能消耗的几个部分
1.数据库连接的建立(使用批量处理);2.数据库编译语句的消耗(使用预处理)
从数据库请求资源时的安全问题
1.预处理可以防止sql注入(语法上);2.事务的使用(逻辑上)

小知识:access 本地数据库,不用监听,(感觉上有点像xml)
   cmd   netstat -an  查看数据监听
预处理的应用----向数据库插入1000条用户信息(不同参数下的相同操作)

<?php
....$id=1;$name="cao";$age=100;$sql="insert into users values(?,?,?)";$mysqli=new MySQLi("localhost","root","root","test");$mysqli_stmt->prepare($sql);$mysqli_stmt->bindparam("isi",$id,$name,$age);  //s代表字符型,i代表数值型$mysqli_stmt->execute() or die("execute error".$mysqli_stmt->error);$id=2;$name="hua";$age=50;$mysqli_stmt->bindparam("isi",$id,$name,$age) ;$mysqli_stmt->execute() or die("execute error".$mysqli_stmt->error);$mysqli_stmt->free();
....
?>

知识点:预处理中如果发生处理错误,预处理会跳过该条数据的处理,继续执行下一条数据的处理。
        预处理发生在dbms。

预处理stmt---dql,打印表

<?php
....$sql="select id ,name ,age from users where id>?";$mysqli=new MySQLi("localhost","root","root","test");if($mysqli->connect_error){die($mysqli->connect_error);}$mysqli_stmt->prepare($sql);$id=5;$mysqli_stmt->bindparam("i",$id);  //参数需要多次绑定$mysqli_stmt->bindresult($id,$name,$age);//此处是按传址绑定。结果集只需要绑定一次。$mysqli_stmt->execute() or die("execute error".$mysqli_stmt->error);while($mysqli_stmt->fetch()){echo"<br/>--$id--$name--$age";}$mysqli_stmt->free_result();$mysqli_stmt->close();     //关闭预编译指令$mysqli->close();
....
?>

小知识:错误日志 error_log
sql   :结构化查询语言(所有数据库的基础)
sql万能密码:aa' or 1='1
密码比对,预处理

mysqli 打印表,

<?php
....echo"has rows".$res->num_rows()."and columns".field_count();echo"<table border='1'><tr>";//从表结构表中获取对应列。foreach($field=$res->fetch_field();){echo"<th>{$field->name}</th>";}</tr>while($row=$res->fetch_row()){echo"<tr>";foreach($row as $key=>$value){echo"<td>{$value}</td>"}echo"</tr>";}echo"</table>";$res->result();
....
?>

小知识:pdo提供一个抽象层。

转载于:https://www.cnblogs.com/Watcher/p/3577496.html

数据库访问 mysql连接库--查询相关推荐

  1. mysql跨库查询 索引_MySQL中跨库查询怎么搞?

    导读 在MySQL中跨库查询主要分为两种情况,一种是同服务的跨库查询;另一种是不同服务的跨库查询;它们进行跨库查询是不同的,下面就具体介绍这两种跨库查询. 在MySQL中跨库查询主要分为两种情况,一种 ...

  2. mysql+join的原理,Mysql连接join查询原理知识点

    Mysql连接join查询原理知识点 Mysql连接(join)查询 1.基本概念 将两个表的每一行,以"两两横向对接"的方式,所得到的所有行的结果. 假设: 表A有n1行,m1列 ...

  3. MYSQL跨库查询的优缺点

    MySQL跨库查询是指在一个MySQL实例中,查询不同数据库之间的数据,其优缺点如下: 优点: 数据库之间可以相互独立,降低数据库之间的耦合性,便于数据库的维护和管理. 在一些需要使用多个数据库的应用 ...

  4. mysql executed_MySQL数据库之mysql从库Retrieved_Gtid_Set事务数比Executed_Gtid_Set事务数少的异常情况...

    本文主要向大家介绍了MySQL数据库之mysql从库Retrieved_Gtid_Set事务数比Executed_Gtid_Set事务数少的异常情况 ,通过具体的内容向大家展现,希望对大家学习MySQ ...

  5. node mysql 跨库查询_nodejs 在mongodb在跨数据库之中如何进行关联起来查询,并且支持筛选关联表的条件进行查询...

    "班级数据库": "mongodb://192.168.3.17/xxx "学生数据库": "mongodb://192.168.3.99/ ...

  6. 两不同服务器上的mysql跨库查询

    业务场景:关联不同数据库中的表的查询 比如说,要关联的表是:机器A上的数据库A中的表A && 机器B上的数据库B中的表B. 这种情况下,想执行"select A.id,B.i ...

  7. mysqli扩展是mysql扩展的增强版_PHP学习笔记【22】--PHP数据库编程 mysql扩展库 和mysqli扩展库...

    <?php         // php数据库编程     //php链接有 mysql 和mysqli    //    $conn  = mysql_connect("localh ...

  8. 【数据库】MySQL多表查询(一)

    练习四(一) 多表查询 一.连接查询 查询女学生的学生学号及总成绩 首先看一下我们jxgl数据库里的表格: 查询女学生的学生学号和总成绩,我们发现sc表里没有性别这一栏,student表里有性别,但是 ...

  9. php如何查询数据库表中数据库,PHP+MYSQL如何进行查询数据库

    PHP+MYSQL进行查询数据库的方法:1.函数[mysql_fetch_object()],从结果集中取得一行作为对象,并将字段名字做为属性:2.函数[mysql_num_rows()]获取由sel ...

最新文章

  1. iBatis简单入门教程
  2. IDEA HTTP状态 404 - 未找到 请求的资源[/]不可用
  3. ocp 042 第十二章:主动维护
  4. [环境搭建]SDN网络感知服务与最短路径应用
  5. [转]从入门到精通,Java学习路线导航
  6. 了解Callable和Spring DeferredResult
  7. Chameleon Install3.0变色龙windows安装程序
  8. 第 19 次 CCF CSP 认证 202006-4 1246(digits)
  9. Linux Ubuntu搭建git服务器
  10. php float转int 元转分
  11. java实现开根号:牛顿迭代法
  12. 全国省市区街道区域信息 API 接口
  13. latch:cbc等待
  14. 基于darknet的voc数据集训练和mAP测试
  15. 会议系统m900服务器网口灯,中兴视频会议mcu服务器zxv10-m900
  16. Java中用for循环输出九九乘法表
  17. 自动驾驶的技术架构和生态发展
  18. Android实现自定义字体
  19. docker部署excalidraw画图工具
  20. VR室内定位系统小结

热门文章

  1. linux下为PHP扩展安装memcache模块
  2. 网站遭遇CC及DDOS攻击紧急处理方案
  3. CSS3 display:flex和display:box有什么区别?
  4. CCNA 02 OSI七层
  5. php-数据分析 余弦相似度实现
  6. Linux 相关发音
  7. SharePoint Server 2007 简单安装指南
  8. 几篇关于Hadoop+Hive数据仓库的入门文章
  9. android SharedPreferences的使用优化
  10. 使用 ArcGIS Desktop 切瓦片