English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
말이 많지 않도록, 구체적인 코드는 다음과 같습니다:
<?php class mysql { private $db_host; //데이터베이스 호스트 private $db_user; //데이터베이스 사용자 이름 private $db_pwd; //데이터베이스 사용자 이름 비밀번호 private $db_database; //데이터베이스 이름 private $conn; //데이터베이스 연결 식별자; private $result; //query 명령어 실행 결과 리소스 식별자 private $sql; //sql 실행 문장 private $row; //반환되는 항목 수 private $coding; //데이터베이스 인코딩, GBK, UTF8,gb2312 private $bulletin = true; //오류 기록을 시작할지 여부 private $show_error = false; //테스트 단계에서 모든 오류를 표시, 보안 위험성이 있음, 기본적으로 꺼짐 private $is_error = false; //오류를 발견했을 때 즉시 중지할지 여부, 기본적으로 true, 권장하지 않음,因为有问题时用户什么也看不到是很苦恼的 /*생성자*/ 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(); } /*데이터베이스 연결*/ public function 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 = 'create database ' . $database; $this->query($sqlDatabase); } /*서버에서 모든 데이터베이스를 쿼리합니다*/ //시스템 데이터베이스와 사용자 데이터베이스를 분리하여 더 직관적으로 표시하려고 합니다? public function show_databases() { $this->query("show databases"); echo "현재 데이터베이스: " . $amount = $this->db_num_rows($rs); echo "<br />"; $i = 1; while ($row = $this->fetch_array($rs)) { echo "\$i $row[Database]"; echo "<br />"; $i++; } } //호스트에서 모든 데이터베이스 이름을 배열 형태로 반환합니다 public function databases() { $rsPtr = mysql_list_dbs($this->conn); $i = 0; $cnt = mysql_num_rows($rsPtr); while ($i < $cnt) { $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 "<br />"; $i = 1; while ($row = $this->fetch_array($rs)) { $columnName = "Tables_in_" . $database_name; echo "\$i $row[$columnName]"; echo "<br />"; $i++; } } /* mysql_fetch_row() array $row[0], $row[1],$row[2, mysql_fetch_array() array $row[0] 또는 $row[id] mysql_fetch_assoc() array를 사용하여 $row->content 필드는 대소문자 구분이 있습니다 mysql_fetch_object() object을 사용하여 $row[id], $row[content] 필드는 대소문자 구분이 있습니다 */ /*결과 데이터를 얻습니다*/ public function mysql_result_li() { return mysql_result($str); } /*레코드 셋을 얻어, 배열을 가져옵니다-INDEX와 관련, 사용 $row['content'] */ public function fetch_array($resultt="") { if($resultt<>"{") return mysql_fetch_array($resultt);} } else { return mysql_fetch_array($this->result); } } //관련 배열 가져오기, $row['필드명'] 사용 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 "<font color='red'>" . $message . "<"/font>"; echo "<br />"; } else { echo "<fieldset>"; echo "<legend>오류 정보 표시:</legend><br />"; echo "<div style='font-size:14px; clear:both; font-family:Verdana, Arial, Helvetica, sans-serif;'>"; echo "<div style='height:20px; background:#000000; border:1px #000000 solid'>"; echo "<font color='white'>오류 번호:12142</font>"; echo "</div><br />"; echo "오류 원인: " . mysql_error() . "<br /><br />"; echo "<div style='height:20px; background:#FF0000; border:1px #FF0000 solid'>"; echo "<font color='white'>" . $message . "</font>"; echo "</div>"; echo "<font color='red'><pre>" . $sql . "</pre></font>"; $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는 0입니다777이는 최대 가능한 접근 권한을 의미합니다 die("업로드 파일 디렉토리가 존재하지 않거나 생성 실패"); } } //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 "<br />"; if ($this->is_error) { exit; } } echo "</div>"; echo "</fieldset>"; echo "<br />"; } //결과 집합을 해제합니다 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 "<br />"; echo "字段수:" . $total = mysql_num_fields($this->result); echo "<pre>"; for ($i = 0; $i < $total; $i++) { print_r(mysql_fetch_field($this->result, $i)); } echo "</pre>"; echo "<br />"; } //MySQL 서버 정보를 가져옵니다 public function mysql_server($num = '') {}} switch ($num) { case 1 : return mysql_get_server_info(); //MySQL 服务器信息 break; case 2 : return mysql_get_host_info(); //取得 MySQL 主机信息 break; case 3 : return mysql_get_client_info(); //取得 MySQL 客户端信息 break; case 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); } //function __destruct(); /*获得客户端真实的IP地址*/ function getip() { if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) { $ip = getenv("HTTP_CLIENT_IP"); } if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) { $ip = getenv("HTTP_X_FORWARDED_FOR"); } if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) { $ip = getenv("REMOTE_ADDR"); } if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) { $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = "unknown"; } return ($ip); } function inject_check($sql_str) { //주입 방지 $check = eregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str); if ($check) { echo "잘못된 주입 내용 입력!"; exit (); } else { return $sql_str; } } function checkurl() { //출처 확인 if (preg_replace("/https?:\/\//,+).*/i1", $_SERVER['HTTP_REFERER']) !== preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])) { header("Location: http://www.dareng.com"); exit(); } } } ?>
위에 설명한 php mysql 패키지 예제 코드는 여러분들에게 도움이 되길 바랍니다. 어떤 질문이든 제게 댓글을 남겨 주시면, 저는 즉시 답변 드리겠습니다. 여기서도 여러분들이 다음을 지원해 주셔서 감사합니다.
선언: 이 문서의 내용은 인터넷에서 가져왔으며, 저작권자는 모두입니다. 내용은 인터넷 사용자가 자발적으로 기여하고 업로드한 것이며, 이 사이트는 소유권을 가지지 않으며, 인공 편집 처리를 하지 않았으며, 관련 법적 책임도 부담하지 않습니다. 저작권 문제가 있는 내용을 발견하시면, notice#w로 이메일을 보내 주시기 바랍니다.3codebox.com(보고할 때는 #을 @으로 변경하십시오. 보고하고 관련 증거를 제공하시면, 해당 내용이 사실로 확인되면, 이 사이트는 즉시 해당 부분을 삭제합니다.)