(25) PHP 随笔---php数据库编程 使用mysql扩展库,编写自己的sqlhelp.class.php
◇如果浏览器显示出的是乱码,我们可以给代码中加入如下语句:
header("Content-type:test/html;charset=utf-8");
◇mysql_fetch_row($res) 返回一个索引数组(推荐使用)
$rows = mysql_fetch_row($res);
◇mysql_fetch_assoc($res) 返回一个关联数组
$rows = mysql_fetch_assoc($res);
◇mysql_fetch_array($res) 返回一个索引和关联数组(两套),比较占用空间
$rows = mysql_fetch_array($res);
◇mysql_fetch_object($res) 把一行数据,当做一个对象返回
$rows = mysql_fetch_object($res);
◇mysql_affected_row($conn) //取得最近一次操作数据库影响的记录行数
$rows = mysql_affected_row($conn); //$i就是上一次对数据库操作影响的记录数
◇mysql_fetch_field($res) //从结果集中取得列信息并作为对象返回,一列一列的取
◇对象的属性有以下:
◇name 列名
◇tabel 表名
◇max_length 该列最大长度
◇primary_key - 1 如果该列是primary key
◇unique_key - 1 如果该列是unique key
◇mysql_num_fields($res) //取回结果集中字段的数目,意思是结果集中一共有多少列
◇mysql_field_name($res) //取得结果中指定字段的名,返回string类型
◇以表格的方式显示数据信息:
1 $colums = mysql_num_fields($res); //得知一共有多少列 2 echo "<table border=1> <tr>"; 3 4 for($i=0;$i<$colums;$i++) 5 { 6 $field_name = mysql_field_name($res,$i); //获得每个字段的字段名 7 echo "<th>$field_name</th>" 8 } 9 echo "</tr>"; 10 11 while($row = mysql_fetch_row($res)) 12 { 13 echo "<tr>"; 14 for($i=0;$i<$colums;$i++) 15 { 16 echo "<td>$row[$i]</td>" 17 } 18 echo "</tr>"; 19 } 20 echo "</table>";
◇使用mysql的扩展库,对数据库进行CRUD操作
◇如果是dml语句,因为它返回的是一个bool值,所以不需要用mysq_free_result()来释放资源。
◇
◇编写一个自己的sqlhelp.class.php:
1 <?php 2 class sqlhelp 3 { 4 private $conn; 5 private $host="localhost"; 6 private $user="root"; 7 private $password="xuweixi"; 8 private $db = "xuweixi"; 9 function sqlhelp() 10 { 11 $this->conn = mysql_connect($this->host,$this->user,$this->password); 12 if(!$this->conn) 13 { 14 die("connect db unsucceed"); 15 } 16 echo "<br/>connecting succeed"; 17 mysql_select_db($this->db,$this->conn); 18 mysql_query("set names utf8"); 19 } 20 function excute_dql($sql) 21 { 22 $res = mysql_query($sql) or die(mysql_error()); 23 return $res; 24 } 25 function excute_dml($sql) 26 { 27 $b = mysql_query($sql,$this->conn); 28 if(!$b) 29 { 30 return 0; 31 } 32 else 33 { 34 if(mysql_affected_rows($this->conn)>0) 35 return 1; 36 else 37 return 2; 38 } 39 } 40 } 41 ?> 42
◇mysql_insert_id //取得上一步insert操作产生的id