封装php数据库表 php 封装( 三 )


}
//返回最近插入的一条数据库的id值
function returnRstId($sql){
if($this-conn == ''){
$this-init_conn();
}
@mysql_query($sql);
if(mysql_errno() == 0){
return mysql_insert_id();
}else{
return '';
}
}
//获取对应的字段值
function getFields($sql,$fields){
$this-mysql_query_rst($sql);
if(mysql_errno() == 0){
if(mysql_num_rows($this-result)0){
$tmpfld = @mysql_fetch_row($this-result);
$this-fields = $tmpfld[$fields];
}
return $this-fields;
}else{
return '';
}
}
//错误信息
function msg_error(){
if(mysql_errno() != 0) {
$this-msg = mysql_error();
}
return $this-msg;
}
//释放结果集
function close_rst(){
mysql_free_result($this-result);
$this-msg = '';
$this-fieldsNum = 0;
$this-rowsNum = 0;
$this-filesArray = '';
$this-rowsArray = '';
}
//关闭数据库
function close_conn(){
$this-close_rst();
mysql_close($this-conn);
$this-conn = '';
}
//取得数据库版本
function db_version() {
return mysql_get_server_info();
}
}
建立conn.php数据库连接,建立一个数据库表建立数据表,得是你在cmd窗口或者phpmyadmin、navicat
for
mysql这类终端软件里进行操作 。建立数据表的指令是create
table
xxx
();
连接数据库使用php封装好的一个函数mysql_connect();
例如:
mysql_connect('127.0.0.1','root','root');
这样的语句来连接,因为连接数据库会生成连接标识资源,你把这个资源赋给一个新变量
$active_connection_sort
=
mysql_connect('127.0.0.1','root','root');
这样你拿着新变量去玩别的也好下手 。
括号中间都是参数,第一个是连接地址 , 比如localhost,但我个人建议还是127.0.0.1省得还得来一步解析,第二个参数是用户名,第三个参数是密码,都用英文单括号括上 。参数和参数之间用英文逗号间隔起来 。
用框架做久了这个东西都容易忘,我也是凭记忆写的,你试试看这个能不能过关 。
PHP中对数据库操作的封装 , 有什么好的例子吗类文件mysql.class.php:
?php
class Mysql{
//数据库连接返回值
private $conn;
/**
* [构造函数,返回值给$conn]
* @param [string] $hostname [主机名]
* @param [string] $username[用户名]
* @param [string] $password[密码]
* @param [string] $dbname[数据库名]
* @param [string] $charset[字符集]
* @return [null]
*/
function __construct($hostname,$username,$password,$dbname,$charset='utf8'){
$config = @mysql_connect($hostname,$username,$password);
if(!$config){
echo '连接失败,请联系管理员';
exit;
}
$this-conn = $config;
$res = mysql_select_db($dbname);
if(!$res){
echo '连接失败,请联系管理员';
exit;
}
mysql_set_charset($charset);
}
function __destruct(){
mysql_close();
}
/**
* [getAll 获取所有信息]
* @param [string] $sql [sql语句]
* @return [array] [返回二维数组]
*/
function getAll($sql){
$result = mysql_query($sql,$this-conn);
$data = https://www.04ip.com/post/array();
if($resultmysql_num_rows($result)0){
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
}
return $data;
}
/**
* [getOne 获取单条数据]
* @param [string] $sql [sql语句]
* @return [array] [返回一维数组]
*/
function getOne($sql){
$result = mysql_query($sql,$this-conn);

推荐阅读