discuz7 phpMysql operation class_PHP tutorial
Jul 21, 2016 pm 03:46 PM
/*
* MySql數(shù)據(jù)庫(kù)連接類
* mysql.class.php 2009.04.15 by Hackbaby
*/
class dbstuff {
var $version = '';
var $querynum = 0;
var $link = null;
//連接數(shù)據(jù)庫(kù)
function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0, $halt = TRUE, $dbcharset2 = '') {
$conn = empty($pconnect) ? 'mysql_connect' : 'mysql_pconnect';
if (!$this->link = @$conn($dbhost, $dbuser, $dbpw, 1)) {
$halt && $this->halt('Can not connect to MySQL server');
} else {
if($this->version() > '4.1') {
global $charset, $dbcharset;
$dbcharset = $dbcharset2 ? $dbcharset2 : $dbcharset;
$dbcharset = !$dbcharset && in_array(strtolower($charset), array('gbk', 'big5', 'utf-8')) ? str_replace('-', '', $charset) : $dbcharset;
$serverset = $dbcharset ? 'character_set_connection='.$dbcharset.', character_set_results='.$dbcharset.', character_set_client=binary' : '';
$serverset .= $this->version() > '5.0.1' ? ((empty($serverset) ? '' : ',').'sql_mode=''') : '';
$serverset && mysql_query("SET $serverset", $this->link);
}
$dbname && @mysql_select_db($dbname, $this->link);
}
}
//選擇數(shù)據(jù)庫(kù)
function select_db($dbname) {
return mysql_select_db($dbname, $this->link);
}
//數(shù)據(jù)庫(kù)執(zhí)行后的返回方法
function fetch_array($query, $result_type = MYSQL_ASSOC) {
return mysql_fetch_array($query, $result_type);
}
//返回fetch_array方法執(zhí)行后的返回值
function fetch_first($sql) {
return $this->fetch_array($this->query($sql));
}
//返回result方法執(zhí)行后的返回值
function result_first($sql) {
return $this->result($this->query($sql), 0);
}
//執(zhí)行對(duì)數(shù)據(jù)庫(kù)的操作
function query($sql, $type = '') {
global $debug, $discuz_starttime, $sqldebug, $sqlspenttimes;
//判斷debug調(diào)試
if(defined('SYS_DEBUG') && SYS_DEBUG) {
@include_once WEB_ROOT.'./include/debug.func.php';
sqldebug($sql);
}
//
$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?
'mysql_unbuffered_query' : 'mysql_query';
if(!($query = $func($sql, $this->link))) {
if(in_array($this->errno(), array(2006, 2013)) && substr($type, 0, 5) != 'RETRY') {
$this->close();
require './config.inc.php';
$this->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, true, $dbcharset);
$this->query($sql, 'RETRY'.$type);
} elseif($type != 'SILENT' && substr($type, 5) != 'SILENT') {
$this->halt('MySQL Query Error', $sql);
}
}
//查詢條數(shù)加1
$this->querynum++;
return $query;
}
//取得前一次 MySQL 操作所影響的記錄行數(shù)
function affected_rows() {
return mysql_affected_rows($this->link);
}
//數(shù)據(jù)庫(kù)的文本錯(cuò)誤提示
function error() {
return (($this->link) ? mysql_error($this->link) : mysql_error());
}
//返回上一個(gè) MySQL 操作中的錯(cuò)誤信息的數(shù)字編碼
function errno() {
return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
}
//返回?cái)?shù)據(jù)庫(kù)操作結(jié)果
function result($query, $row = 0) {
$query = @mysql_result($query, $row);
return $query;
}
//返回?cái)?shù)據(jù)庫(kù)查詢等操作的數(shù)目
function num_rows($query) {
$query = mysql_num_rows($query);
return $query;
}
//取得結(jié)果集中字段的數(shù)目
function num_fields($query) {
return mysql_num_fields($query);
}
//釋放結(jié)果內(nèi)存
function free_result($query) {
return mysql_free_result($query);
}
//取得上一步 INSERT 操作產(chǎn)生的 ID
function insert_id() {
return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
}
//以數(shù)組的形式返回查詢結(jié)果
function fetch_row($query) {
$query = mysql_fetch_row($query);
return $query;
}
//從結(jié)果集中取得列信息并作為對(duì)象返回
function fetch_fields($query) {
return mysql_fetch_field($query);
}
//獲取Mysql的版本
function version() {
if(empty($this->version)) {
$this->version = mysql_get_server_info($this->link);
}
return $this->version;
}
//關(guān)閉連接
function close() {
return mysql_close($this->link);
}
//錯(cuò)誤提示
function halt($message = '', $sql = '') {
define('CACHE_FORBIDDEN', TRUE);
require_once WEB_ROOT . './include/db_mysql_error.inc.php';
}
}
?>

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

CTE is a temporary result set in MySQL used to simplify complex queries. It can be referenced multiple times in the current query, improving code readability and maintenance. For example, when looking for the latest orders for each user in the orders table, you can first obtain the latest order date for each user through the CTE, and then associate it with the original table to obtain the complete record. Compared with subqueries, the CTE structure is clearer and the logic is easier to debug. Usage tips include explicit alias, concatenating multiple CTEs, and processing tree data with recursive CTEs. Mastering CTE can make SQL more elegant and efficient.

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

There are three key ways to avoid the "undefinedindex" error: First, use isset() to check whether the array key exists and ensure that the value is not null, which is suitable for most common scenarios; second, use array_key_exists() to only determine whether the key exists, which is suitable for situations where the key does not exist and the value is null; finally, use the empty merge operator?? (PHP7) to concisely set the default value, which is recommended for modern PHP projects, and pay attention to the spelling of form field names, use extract() carefully, and check the array is not empty before traversing to further avoid risks.

When using PHP preprocessing statements to execute queries with IN clauses, 1. Dynamically generate placeholders according to the length of the array; 2. When using PDO, you can directly pass in the array, and use array_values to ensure continuous indexes; 3. When using mysqli, you need to construct type strings and bind parameters, pay attention to the way of expanding the array and version compatibility; 4. Avoid splicing SQL, processing empty arrays, and ensuring data types match. The specific method is: first use implode and array_fill to generate placeholders, and then bind parameters according to the extended characteristics to safely execute IN queries.

WhensettingupMySQLtables,choosingtherightdatatypesiscrucialforefficiencyandscalability.1)Understandthedataeachcolumnwillstore—numbers,text,dates,orflags—andchooseaccordingly.2)UseCHARforfixed-lengthdatalikecountrycodesandVARCHARforvariable-lengthdata

Reasons and solutions for the header function jump failure: 1. There is output before the header, and all pre-outputs need to be checked and removed or ob_start() buffer is used; 2. The failure to add exit causes subsequent code interference, and exit or die should be added immediately after the jump; 3. The path error should be used to ensure correctness by using absolute paths or dynamic splicing; 4. Server configuration or cache interference can be tried to clear the cache or replace the environment test.
