您的位置:首页 > 编程语言 > PHP开发

php基础知识【函数】(6)mysql数据库

2014-09-14 17:05 531 查看
一、连接和关闭

1、mysql_connect('example.com:3307', 'root', '123456') --打开一个到 MySQL 服务器的非永久连接

2、mysql_pconnect(server,user,pwd,clientflag) --打开一个到 MySQL 服务器的持久连接。

参数:

server 可选。规定要连接的服务器。

user 可选。用户名。默认值是服务器进程所有者的用户名。

pwd 可选。密码。默认值是空密码。

clientflag 可选。client_flags 参数可以是以下常量的组合:

MYSQL_CLIENT_SSL - 使用 SSL 加密

MYSQL_CLIENT_COMPRESS - 使用压缩协议

MYSQL_CLIENT_IGNORE_SPACE - 允许函数名后的间隔

MYSQL_CLIENT_INTERACTIVE - 允许关闭连接之前的交互超时非活动时间

3、mysql_free_result(data) --将释放所有与结果标识符 result 所关联的内存。

仅需要在考虑到返回很大的结果集时会占用多少内存时调用。在脚本结束后所有关联的内存都会被自动释放。

4、mysql_close(link_identifier) --关闭 MySQL 连接,通常不需要,因为已打开的非持久连接会在脚本执行完毕后自动关闭。如果没有指定 link_identifier,则关闭上一个打开的连接。

$link = mysql_connect('example.com:3307', 'root', '123456');

if (!$link) {

die('Could not connect: ' . mysql_error());

}

echo 'Connected successfully';

mysql_close($link);

二、设置数据库

1、mysql_select_db(database,connection) --设置活动的 MySQL 数据库。

2、mysql_query("set names 'utf8'"); --设置数据库编码

3、mysql_client_encoding([resource link_identifier]) --从 MySQL 中取得 character_set 变量的值。

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$charset = mysql_client_encoding($link);

三、执行sql语句

1、mysql_query(query,connection) --执行一条 MySQL 查询。

2、mysql_unbuffered_query(query,connection) --向 MySQL 发送一条 SQL 查询(不获取 / 缓存结果)。

参数:

query 必需。规定要发送的 SQL 查询。注释:查询字符串不应以分号结束。

connection 可选。规定 SQL 连接标识符。如果未规定,则使用上一个打开的连接。

好处:

mysql_unbuffered_query() 向 MySQL 发送一条 SQL 查询 query ,但不像 mysql_query() 那样自动获取并缓存结果集。

一方面,这在处理很大的结果集时会节省可观的内存。

另一方面,可以在获取第一行后立即对结果集进行操作,而不用等到整个 SQL 语句都执行完毕。

代价:

在 mysql_unbuffered_query() 返回的结果集之上不能使用 mysql_num_rows() 和 mysql_data_seek()。

此外在向 MySQL 发送一条新的 SQL 查询之前,必须提取所有未缓存的 SQL 查询所产生的结果行。

3、mysql_real_escape_string(string,connection) --转义 SQL 语句中使用的字符串中的特殊字符。

可使用本函数来预防数据库攻击。将 string 中的特殊字符转义,并考虑到连接的当前字符集,因此可以安全用于 mysql_query()。

// 转义用户名和密码,以便在 SQL 中使用

$user = mysql_real_escape_string($user);

$pwd = mysql_real_escape_string($pwd);

$sql = "SELECT * FROM users WHERE user='" . $user . "' AND password='" . $pwd . "'"

四、从结果集取得信息【fetch】

参数:

data 必需。要使用的数据指针。该数据指针是从 mysql_query() 返回的结果。

array_type 可选。规定返回哪种结果。可能的值MYSQL_ASSOC【关联数组】、MYSQL_NUM【 数字数组】、MYSQL_BOTH【默认。同时产生关联和数字数组】

field_offset 必需。指示从哪个字段开始返回。0 指示第一个字段。

1、mysql_fetch_row(data) --从结果集中取得【一行】作为枚举数组,用循环来做每一次会移动到下查询结果中的下一行

2、mysql_fetch_array(data,array_type) --从结果集取得的【一行】作为关联数组,或数字数组,或二者兼有,返回的字段名区分大小写。

3、mysql_fetch_assoc(data) --从结果集中取得【一行】作为关联数组,返回的字段名区分大小写

4、mysql_fetch_lengths(data) --取得【一行】中【每个】字段的内容的长度。

5、mysql_fetch_object(data) --从结果集中取得一行作为对象,本函数返回的字段名是区分大小写的。

6、mysql_fetch_field(data,field_offset) --从结果集中取得列属性并作为对象返回【可多个】

被返回的对象的属性为:

name - 列名 W

table - 该列所在的表名

max_length - 该列最大长度

not_null - 1,如果该列不能为 NULL

primary_key - 1,如果该列是 primary key

unique_key - 1,如果该列是 unique key

multiple_key - 1,如果该列是 non-unique key

numeric - 1,如果该列是 numeric

blob - 1,如果该列是 BLOB

type - 该列的类型

unsigned - 1,如果该列是无符号数

zerofill - 1,如果该列是 zero-filled

7、mysql_num_fields(data) --返回结果集中【字段】的数。

8、mysql_num_rows(data) --返回结果集中【行】的数目。

9、mysql_result(data,row,field) --返回结果集中一个字段的值。

参数:

data 必需。规定要使用的结果标识符。该标识符是 mysql_query() 函数返回的。

row 必需。规定行号。行号从 0 开始。

field 可选。规定获取哪个字段。可以是字段偏移值,字段名或 table.fieldname。如果该参数未规定,则该函数从指定的行获取第一个字段。

备注:

当作用于很大的结果集时,应该考虑使用能够取得整行的函数。这些函数在一次函数调用中返回了多个单元的内容,比 mysql_result() 快得多。

此外请注意,在字段参数中指定数字偏移量比指定字段名或者 tablename.fieldname 要快得多。

五、获取指定字段的信息【field】

参数:

data 必需。要使用的数据指针。该数据指针是从 mysql_query() 返回的结果。

field_offset 必需。指示从哪个字段开始返回。0 指示第一个字段。

1、mysql_field_len(data,field_offset) --取得字段的长度

$result = mysql_query("SELECT * from Person");

$length = mysql_field_len($result, 0); //20

2、mysql_field_name(data,field_offset) --取得字段索引的字段名,返回的字段名区分大小写。

$result = mysql_query("SELECT * from Person");

$length = mysql_field_name($result, 0); //20

3、mysql_field_table(data,field_offset) --取得字段所在的表名

$result = mysql_query("SELECT * from Person");

$length = 3、mysql_field_table($result, 0); //Person

4、mysql_field_type(data,field_offset) --取得字段的类型

$result = mysql_query("SELECT * from Person");

$length = 3、mysql_field_table($result, 0); //string

5、mysql_field_flags(data,field_offset) --取得字段的字段标志。每个标志都用空格+单词分开,可用 explode()将其分开。

例子:

$result = mysql_query("SELECT * from Person");

$length = mysql_field_flags($result, 0); //not_null primary_key auto_increment

备注:

如果 MySQL 版本足够新,则会支持以下的标志:

auto_intcrement binary blob enum multiple_key not_null primary_key timestamp unique_key unsigned zerofill

6、mysql_field_seek(data,field_offset) --将结果集中的指针设定为制定的字段偏移量

例子:

$result = mysql_query("SELECT * from Person");

$length = mysql_field_seek($result, 3); //// 跳到第四个字段

六、其他:

1、mysql_insert_id(connection) --返回上一步 INSERT 操作产生的 ID。如果没有产生 AUTO_INCREMENT 的 ID,则返回 0。

2、mysql_list_dbs(connection) --列出 MySQL 服务器中所有的数据库。

3、mysql_list_processes(connection) --列出 MySQL 进程。

4、mysql_thread_id(connection) --返回当前线程的 ID。

5、mysql_ping(connection) --Ping 一个服务器连接,如果没有连接则重新连接。

6、mysql_info(connection) --返回最近一条查询的信息。 //返回的结果类似:String format: Records: 15 Duplicates: 0 Warnings: 0

7、mysql_affected_rows(link_identifier) -- 取得前一次 MySQL 操作所影响的记录行数,如果没有指定link_identifier,默认使用最后打开的连接。

执行成功则返回受影响的行的数目,如果最近一次查询失败的话,函数返回 -1。

PDATE 查询:MySQL 不会将原值和新值一样的列更新。只有真正被修改的记录数才会被返回。

REPLACE 语句:本函数返回的是被删除的记录数加上被插入的记录数。

8、mysql_db_name(list,row,field)-将调用 mysql_list_dbs() 返回的结果指针作为第一个参数。row 参数是结果集中的一个索引。

参数:

list 必需。mysql_list_dbs() 调用所返回的结果指针。

row 必需。规定结果集中的行号。以 0 开始。

field 可选。规定字段名。

9、mysql_data_seek(data,row) --移动内部结果的指针,调用 mysql_fetch_row() 将返回那一行。

参数:

data 必需。返回类型为 resource 的结果集。该结果集从 mysql_query() 的调用中得到。

row 必需。想要设定的新的结果集指针的行数。0 指示第一个记录。

例子:

$result = mysql_query("SELECT * from Person"$con);

mysql_data_seek($result,3);

print_r(mysql_fetch_row($result));

备注:

row_number 从 0 开始。row_number 的取值范围应该从 0 到 mysql_num_rows - 1

mysql_data_seek() 只能和 mysql_query() 结合起来使用,而不能用于 mysql_unbuffered_query()

七、获取mysql系统信息

1、mysql_get_client_info() 取得 MySQL 客户端信息。

2、mysql_get_host_info() 取得 MySQL 主机信息。

3、mysql_get_proto_info() 取得 MySQL 协议信息。

4、mysql_get_server_info() 取得 MySQL 服务器信息。

5、mysql_stat(connection) 取得 MySQL 服务器的当前系统状态。

八、错误提示

1、mysql_errno() --返回上一个 MySQL 函数的错误号码,如果没有出错则返回 0(零)。

2、mysql_error() --回上一个 MySQL 函数的错误文本,如果没有出错则返回 ''(空字符串)。

九、已不赞成使用的

1、mysql_change_user(newuser,password,database) --改变活动连接中登录的用户

2、mysql_create_db() --新建 MySQL 数据库。使用 mysql_query() 代替

3、mysql_db_query() --发送一条 MySQL 查询。使用 mysql_select_db() 和 mysql_query() 代替。

4、mysql_drop_db() --丢弃(删除)一个 MySQL 数据库。使用 mysql_query() 代替。

5、mysql_escape_string() --转义一个字符串用于 mysql_query。使用 mysql_real_escape_string() 代替。

6、mysql_list_tables() --列出 MySQL 数据库中的表。使用Use mysql_query() 代替。

7、mysql_tablename() --取得表名。使用 mysql_query() 代替。

十、一个例子


//链接数据库

  $con = mysql_connect("localhost", "hello", "321");

   if (!$con){

   die('Could not connect: ' . mysql_error());

   }

//选择数据库

  $db_selected = mysql_select_db("test_db",$con);

//设置数据库编码

   mysql_query("set names 'utf8'");

//sql语句

   $sql = "SELECT * from Person";

//执行sql语句

   $result = mysql_query($sql,$con);

// 获取一行查询结果

  $row=mysql_fetch_row($result);

/// 显示字段名称

   for ($i=0; $i<mysql_num_fields($result); $i++){

     mysql_field_name($result,$i);

   }

// 定位到第一条记录

   mysql_data_seek($result, 0);

// 循环取出记录

  while ($row=mysql_fetch_row($result)){

  for ($i=0; $i<mysql_num_fields($result); $i++ ){

   echo $row[$i];

   }

   }

//把查询结果放到一个数组中

   while ($row=mysql_fetch_row($result)){

   $arr[]=$row;

   }

// 释放资源

  mysql_free_result($result);

// 关闭连接

  mysql_close($conn);



十二:一个MySql类

////////////config.db.php


$db_config["hostname"] = "localhost"; //服务器地址

$db_config["username"] = "root"; //数据库用户名

$db_config["password"] = "123456"; //数据库密码

$db_config["database"] = "test"; //数据库名称

$db_config["charset"] = "utf8"; //数据库编码

$db_config["pconnect"] = 1; //开启持久连接

$db_config["log"] = 1; //开启日志

$db_config["logfilepath"] = './'; //日志地址


/////////////Db.php


Class DB {

private $link_id;

private $handle;

private $is_log;

private $time;

//构造函数

public function __construct() {

$this->time = $this->microtime_float();

require_once("config.db.php");

$this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]);

$this->is_log = $db_config["log"];

if($this->is_log){

$handle = fopen($db_config["logfilepath"]."dblog.txt", "a+");

$this->handle=$handle;

}

}

//数据库连接

public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0,$charset='utf8') {

if( $pconnect==0 ) {

$this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);

if(!$this->link_id){

$this->halt("数据库连接失败");

}

} else {

$this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw);

if(!$this->link_id){

$this->halt("数据库持久连接失败");

}

}

if(!@mysql_select_db($dbname,$this->link_id)) {

$this->halt('数据库选择失败');

}

@mysql_query("set names ".$charset);

}

//查询

public function query($sql) {

$this->write_log("查询 ".$sql);

$query = mysql_query($sql,$this->link_id);

if(!$query) $this->halt('Query Error: ' . $sql);

return $query;

}

//获取一条记录(MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH)

public function get_one($sql,$result_type = MYSQL_ASSOC) {

$query = $this->query($sql);

$rt =& mysql_fetch_array($query,$result_type);

$this->write_log("获取一条记录 ".$sql);

return $rt;

}

//获取全部记录

public function get_all($sql,$result_type = MYSQL_ASSOC) {

$query = $this->query($sql);

$i = 0;

$rt = array();

while($row =& mysql_fetch_array($query,$result_type)) {

$rt[$i]=$row;

$i++;

}

$this->write_log("获取全部记录 ".$sql);

return $rt;

}

//插入

public function insert($table,$dataArray) {

$field = "";

$value = "";

if( !is_array($dataArray) || count($dataArray)<=0) {

$this->halt('没有要插入的数据');

return false;

}

while(list($key,$val)=each($dataArray)) {

$field .="$key,";

$value .="'$val',";

}

$field = substr( $field,0,-1);

$value = substr( $value,0,-1);

$sql = "insert into $table($field) values($value)";

$this->write_log("插入 ".$sql);

if(!$this->query($sql)) return false;

return true;

}

//更新

public function update( $table,$dataArray,$condition="") {

if( !is_array($dataArray) || count($dataArray)<=0) {

$this->halt('没有要更新的数据');

return false;

}

$value = "";

while( list($key,$val) = each($dataArray))

$value .= "$key = '$val',";

$value .= substr( $value,0,-1);

$sql = "update $table set $value where 1=1 and $condition";

$this->write_log("更新 ".$sql);

if(!$this->query($sql)) return false;

return true;

}

//删除

public function delete( $table,$condition="") {

if( empty($condition) ) {

$this->halt('没有设置删除的条件');

return false;

}

$sql = "delete from $table where 1=1 and $condition";

$this->write_log("删除 ".$sql);

if(!$this->query($sql)) return false;

return true;

}

//返回结果集

public function fetch_array($query, $result_type = MYSQL_ASSOC){

$this->write_log("返回结果集");

return mysql_fetch_array($query, $result_type);

}

//获取记录条数

public function num_rows($results) {

if(!is_bool($results)) {

$num = mysql_num_rows($results);

$this->write_log("获取的记录条数为".$num);

return $num;

} else {

return 0;

}

}

//释放结果集

public function free_result() {

$void = func_get_args();

foreach($void as $query) {

if(is_resource($query) && get_resource_type($query) === 'mysql result') {

return mysql_free_result($query);

}

}

$this->write_log("释放结果集");

}

//获取最后插入的id

public function insert_id() {

$id = mysql_insert_id($this->link_id);

$this->write_log("最后插入的id为".$id);

return $id;

}

//关闭数据库连接

protected function close() {

$this->write_log("已关闭数据库连接");

return @mysql_close($this->link_id);

}

//错误提示

private function halt($msg='') {

$msg .= "\r\n".mysql_error();

$this->write_log($msg);

die($msg);

}

//析构函数

public function __destruct() {

$this->free_result();

$use_time = ($this-> microtime_float())-($this->time);

$this->write_log("完成整个查询任务,所用时间为".$use_time);

if($this->is_log){

fclose($this->handle);

}

}

//写入日志文件

public function write_log($msg=''){

if($this->is_log){

$text = date("Y-m-d H:i:s")." ".$msg."\r\n";

fwrite($this->handle,$text);

}

}

//获取毫秒数

public function microtime_float() {

list($usec, $sec) = explode(" ", microtime());

return ((float)$usec + (float)$sec);

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: