[PHP] 코드
class mysql {
private $db_host; //데이터베이스 호스트
private $db_user; //데이터베이스 사용자 이름
private $ db_pwd; //데이터베이스 사용자 이름 및 비밀번호
private $db_database; //데이터베이스 이름
private $conn; //데이터베이스 연결 식별자;
private $result; command
private $sql; //SQL 실행 문
private $row; //반환된 항목 수
private $coding; //데이터베이스 인코딩, GBK, UTF8, gb2312
private $bulletin true; / /오류 로깅 활성화 여부
private $show_error = false; //테스트 단계에서는 보안 위험이 있는 모든 오류가 표시됩니다.
private $is_error = false ; //오류 발견 시 즉시 종료할지 여부, 기본값은 true, 권장 문제가 있을 때 사용자에게 아무것도 표시되지 않는 것이 매우 답답하기 때문에 활성화하지 않음
/*Constructor*/
public function __construct($db_host, $db_user, $db_pwd, $db_database, $ conn, $coding) {
$this->db_host = $db_host;
$this->db_user = $db_user;
$this->db_pwd = $db_pwd;
$this ->db_database = $db_database;
$this->conn = $conn;
$this->coding = $coding;
$this->connect();
}
/*데이터베이스 연결*/
공용 함수 connect() {
if ($this->conn == "pconn") {
//영구 링크
$ this->conn = mysql_pconnect($this->db_host, $this->db_user, $this->db_pwd);
} else {
//링크가
$this-> ;conn = mysql_connect($this->db_host, $this->db_user, $this->db_pwd);
}
if (!mysql_select_db($this->db_database, $this->conn)) {
if ($this->show_error) {
$this->show_error( "데이터베이스를 사용할 수 없음:", $this->db_database);
}
}
mysql_query("SET NAMES $this->coding");
}
/*데이터베이스 실행문, 실행 쿼리, 추가, 수정, 삭제 등 모든 SQL 문*/
public function query($sql) {
if ($sql == "") {
$ this->show_error("SQL 문 오류:", "SQL 쿼리 문이 비어 있습니다.");
}
$this->sql = $sql;
$result = mysql_query( $this->sql, $this->conn);
if ( !$result) {
//디버깅에 사용되며 SQL 문에서 오류가 발생하면 자동으로 인쇄됩니다.
if ($this->show_error) {
$this->show_error("오류 SQL 문: ", $this->sql);
}
} else {
$this->result = $result;
}
return $this->result;
}
/*새 데이터베이스 생성 및 추가*/
public function create_database($database_name) {
$database = $database_name;
$sqlDatabase = '데이터베이스 생성' .
$this->query($sqlDatabase);
}
/*서버의 모든 데이터베이스 쿼리*/
//보다 직관적인 표시를 위해 시스템 데이터베이스와 사용자 데이터베이스를 분리 ?
공개 함수 show_databases() {
$this->query("showdatabases");
echo "기존 데이터베이스:" . $amount = $this->db_num_rows($rs); 🎜> echo " ";
$i = 1;
while ($row = $this->fetch_array($rs)) {
echo "$i $row [ Database]";
echo " ";
$i ;
}
}
//호스트에 있는 모든 데이터베이스 이름을 배열 형식으로 반환
공용 함수 데이터베이스() {
$rsPtr = mysql_list_dbs($this->conn);
$i = 0;
$cnt = mysql_num_rows($rsPtr);
while($ i $rs[] = mysql_db_name($rsPtr, $i);
$i ;
}
return $rs;
}
/*데이터베이스 아래의 모든 테이블 쿼리*/
public function show_tables($database_name) {
$this->query("show tables");
echo "기존 데이터베이스:" $ amount. = $this->db_num_rows($rs);
echo " ";
$i = 1;
while ($row = $this->fetch_array($ rs )) {
$columnName = "테이블_in_" . $database_name;
echo "$i $row[$columnName]";
echo " ";
$i ;
}
}
/*
mysql_fetch_row() 배열 $row[0],$row[1],$row[2]
mysql_fetch_array() 배열 $row [ 0] 또는 $row[id]
mysql_fetch_assoc() 배열은 $row->content 필드 대소문자 구분을 사용합니다.
mysql_fetch_object() 객체는 $row[id],$row[content] 필드 대소문자 구분을 사용합니다.
*/
/*결과 데이터 가져오기*/
public function mysql_result_li() {
return mysql_result($str);
}
/*Get Recordset, get 배열 인덱스 및 연관, $row['content'] 사용 */
public function fetch_array($resultt="") {
if($resultt""){
return mysql_fetch_array( $resultt);
}else{
return mysql_fetch_array($this->result);
}
}
//연관 배열을 가져오고 $ row['를 사용합니다. field name']
public function fetch_assoc() {
return mysql_fetch_assoc($this->result);
}
//숫자 인덱스 배열을 가져오고 $row [0 사용 ],$row[1],$row[2]
public function fetch_row() {
return mysql_fetch_row($this->result);
}
// 가져오려면 객체 배열, $row->content 사용
public function fetch_Object() {
return mysql_fetch_object($this->result);
}
//단순 쿼리 select
public function findall($table) {
$this->query("SELECT * FROM $table");
}
//간단한 쿼리 select
public function select ($table, $columnName = "*", $condition = '', $debug = '') {
$condition = $condition ? ' Where ' . $condition : NULL;
if ($debug) {
echo "SELECT $columnName FROM $table $condition";
} else {
$this->query("SELECT $columnName FROM $table $condition");
}
}
//간단한 삭제 del
public function delete($table, $condition, $url = '') {
if ($this->query("DELETE FROM $table WHERE $condition")) {
if (!empty ($url))
$this->Get_admin_msg($url, '삭제에 성공했습니다! ');
}
}
//단순 삽입 insert
public function insert($table, $columnName, $value, $url = '') {
if ( $this->query("INSERT INTO $table ($columnName) VALUES ($value)")) {
if (!empty ($url))
$this->Get_admin_msg($url, '성공적으로 추가되었습니다!');
}
}
//简化修改update
public function update($table, $mod_content, $condition, $url = '') {
//echo "UPDATE $table SET $mod_content WHERE $condition"; exit();
if ($this->query("UPDATE $table SET $mod_content WHERE $condition")) {
if (!empty ($url))
$this->Get_admin_msg($url);
}
}
/*取得上一步 INSERT 操作产生的 ID*/
public function insert_id() {
return mysql_insert_id();
}
//指向确定的一条数据记录
public function db_data_seek($id) {
if ($id > 0) {
$id = $id -1;
}
if (!@ mysql_data_seek($this->result, $id)) {
$this->show_error("SQL语句有误:", "指定的数据为空");
}
return $this->result;
}
// 根据select查询结果计算结果集条数
public function db_num_rows() {
if ($this->result == null) {
if ($this->show_error) {
$this->show_error("SQL语句错误", "暂时为空,没有任何内容!");
}
} else {
return mysql_num_rows($this->result);
}
}
// 根据insert,update,delete执行结果取得影响行数
public function db_affected_rows() {
return mysql_affected_rows();
}
//输出显示sql语句
public function show_error($message = "", $sql = "") {
if (!$sql) {
echo "" . $message . " ";
echo " ";
} else {
echo ""; echo "错误信息提示:
";
echo "";
echo "";
echo "错误号:12142 ";
echo "
";
echo "错误原因:" . mysql_error() . " ";
echo "";
echo "" . $message . " ";
echo "
";
echo "" . $sql . " ";
$ip = $this->getip();
if ($this->bulletin) {
$time = date("Y-m-d H:i:s");
$message = $message . "\r\n$this->sql" . "\r\n客户IP:$ip" . "\r\n时间 :$time" . "\r\n\r\n";
$server_date = date("Y-m-d");
$filename = $server_date . ".txt";
$file_path = "error/" . $filename;
$error_content = $message;
//$error_content="错误的数据库,不可以链接";
$file = "error"; //设置文件保存目录
//建立文件夹
if (!file_exists($file)) {
if (!mkdir($file, 0777)) {
//默认的 mode 是 0777,意味着最大可能的访问权
die("upload files directory does not exist and creation failed");
}
}
//建立txt日期文件
if (!file_exists($file_path)) {
//echo "建立日期文件";
fopen($file_path, "w+");
//首先要确定文件存在并且可写
if (is_writable($file_path)) {
//使用添加模式打开$filename,文件指针将会在文件的开头
if (!$handle = fopen($file_path, 'a')) {
echo "不能打开文件 $filename";
exit;
}
//将$somecontent写入到我们打开的文件中。
if (!fwrite($handle, $error_content)) {
echo "不能写入到文件 $filename";
exit;
}
//echo "文件 $filename 写入成功";
echo "——错误记录被保存!";
//关闭文件
fclose($handle);
} else {
echo "文件 $filename 不可写";
}
} else {
//首先要确定文件存在并且可写
if (is_writable($file_path)) {
//使用添加模式打开$filename,文件指针将会在文件的开头
if (!$handle = fopen($file_path, 'a')) {
echo "不能打开文件 $filename";
exit;
}
//将$somecontent写入到我们打开的文件中。
if (!fwrite($handle, $error_content)) {
echo "不能写入到文件 $filename";
exit;
}
//echo "文件 $filename 写入成功";
echo "——错误记录被保存!";
//关闭文件
fclose($handle);
} else {
echo "文件 $filename 不可写";
}
}
}
echo " ";
if ($this->is_error) {
exit;
}
}
echo "
";
echo "
";
echo " ";
}
//결과 세트 해제
public function free() {
@ mysql_free_result($this->result);
}
//데이터베이스 선택
public function select_db($db_database) {
return mysql_select_db ( $db_database);
}
//필드 수 쿼리
public function num_fields($table_name) {
//return mysql_num_fields($this->result);
$ this->query("select * from $table_name");
echo " ";
echo "필드 수:" . $total = mysql_num_fields($this- >result) ;
echo "";
for ($i = 0; $i print_r(mysql_fetch_field($this->result , $i) );
}
echo "";
echo " ";
}
//MySQL 서버 가져오기 information
public function mysql_server($num = '') {
스위치($num) {
사례 1 :
return mysql_get_server_info() //MySQL 서버 정보
break;
사례 2 :
return mysql_get_host_info(); //MySQL 호스트 정보 가져오기
break;
사례 3 :
return mysql_get_client_info(); //MySQL 클라이언트 정보 가져오기
break ;
사례 4 :
return mysql_get_proto_info(); //MySQL 프로토콜 정보 가져오기
break;
default :
return mysql_get_client_info() // 기본적으로 mysql 버전 정보 가져오기
}
}
//소멸자, 데이터베이스 자동 닫기, 가비지 수집 메커니즘
public function __destruct() {
if (!empty ($ this->result)) {
$this->free();
}
mysql_close($this->conn);
} //함수 __destruct();
/*클라이언트의 실제 IP 주소 가져오기*/
function getip() {
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
$ip = getenv("HTTP_CLIENT_IP");
} else
if (getenv("HTTP_X_FORWARDED_FOR") &&strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "알 수 없음")) {
$ip = getenv(" HTTP_X_FORWARDED_FOR");
} else
if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "알 수 없음")) {
$ip = getenv("REMOTE_ADDR ");
} else
if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] &&strcasecmp($_SERVER['REMOTE_ADDR'], "알 수 없음")) {
$ip = $ _SERVER['REMOTE_ADDR'];
} else {
$ip = "알 수 없음";
}
return ($ip);
}
function inject_check( $sql_str) { //삽입 방지
$check =eregi('select|insert|update|delete|'|/*|*|../|./|union|into|load_file|outfile',$sql_str );
if ($check) {
echo "불법 주입 내용을 입력하세요! ";
종료 ();
} else {
return $sql_str;
}
}
function checkurl() { //소스 확인
if (preg_replace( "/https?://([^:/] ).*/i", "\1", $_SERVER['HTTP_REFERER']) !== preg_replace("/([^:] ).*/" , "\1", $_SERVER['HTTP_HOST'])) {
header("위치: http://www.dareng.com");
exit();
}
}
}
?>
코드 복사