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

PHP连接MySQL

2009-11-26 08:56 288 查看
<?php

/**
* Mysql DB
*
* @author Administrator
* @package defaultPackage
*/
class MySqlDB{
private $_db;
private static $_instance;
private function __construct(&$db_type){
global $connectionstr;
$conn_db=$connectionstr[$db_type];
$this->_db=mysql_pconnect($conn_db["servername"],$conn_db["usernmae"],$conn_db["pwd"]);
if(!$this->_db){
die("'Could not connect: ".mysql_error());
}
mysql_select_db($conn_db["dbname"],$this->_db);
}
private function __clone(){

}
public static function getInstance(&$db_type){
if(!(self::$_instance instanceof self)){
self::$_instance=new self($db_type);
}
return self::$_instance;
}
function query($sql){
mysql_query("SET NAMES 'GBK'",$this->_db);
return mysql_query($sql,$this->_db);
}
function get_result_sql($sql){
return $this->query($sql);
}
/***根据sql,返回数组数据,有错误提示***/
function getarray($sql){
$result_ay=array();
if($re=$this->query($sql)){
while ($row=mysql_fetch_array($re)) {
$result_ay[]=$row;
}
}
else {
js_msg("数据访问有错!",-1);
}
return $result_ay;
}
/***根据sql,返回数组数据***/
function getarray_no_msg($sql){
$result_ay=array();
if($re=$this->query($sql)){
while ($row=mysql_fetch_array($re)) {
$result_ay[]=$row;
//mysql_fetch_array,mysql_fetch_row,
}
}
return $result_ay;
}
/***批量查询,字段相同,返回一数组***/
function getarray_sqls($sql){
$result_ay=array();
if(is_array($sql)){
//print_r($sql);
foreach ($sql as $k=>$v){
if($re=$this->query($v)){
while ($row=mysql_fetch_array($re)) {
$result_ay[]=$row;
}
}
}
}
else {
$result_ay=$this->getarray_no_msg($sql);
}
return $result_ay;
}
/**
* 获取多个结果集
*
* @param array sqls
* @return array
*/
function getarrays_sqls($sql){
$result_ay=array();
if(is_array($sql)){
foreach ($sql as $k=>$v){
$temary=array();
if($re=$this->query($v)){
while ($row=mysql_fetch_array($re)) {
$temary[]=$row;
}
}
$result_ay[]=$temary;
}
}
else {
$result_ay=$this->getarray_no_msg($sql);
}
return $result_ay;
}
/***返回第一行第一列***/
function ExecuteScalar($sql){
if($re=$this->query($sql)){
$row=mysql_fetch_row($re);
return $row[0];
}
else {
//echo $sql;
die("sql执行错误!");
}
}
/***执行Sql***/
function ExecSql($sql,$IsLastId=false){
if(is_array($sql)){
//多条sql
$t=0;//成功
foreach ($sql as $k=>$v){
if(!empty($v)){
if($re=$this->query($v)){
$t=$t+mysql_affected_rows();
}
}
}
return $t;
}
else{
//执行单条sql
if($re=$this->query($sql)){
if($IsLastId){
return $this->last_id($this->query("select last_insert_id()"));
}
else {
return  mysql_affected_rows();
}
}
else {
mysql_error();
die("数据执行错误!");
return 0;
}
}
}
function fetchrows($sql){
$result_ay=array();
if($re=$this->query($sql)){
while ($row=mysql_fetch_array($re,MYSQL_ASSOC)) {
$result_ay[]=$row;
}
}
return $result_ay;
}
function last_id(&$re){
$id=0;
while ($row=mysql_fetch_row($re)){
$id=$row[0];
}
return $id;
}
}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息