php MYSQL數(shù)據(jù)操作類
Jun 13, 2016 am 10:56 AM
mysql 數(shù)據(jù)庫操作類,分享給大家
[php]
/**
?*db.class.php create databse object
?*
?*@author Dick 417@668x.net
?*@copyright http://blog.csdn.net/haibrother
?*
?**/?
?
class Dick_Db{?
??? public? $db_host??????? = ''; //主機地址??
??? public? $db_username??? = ''; //數(shù)據(jù)庫帳號??
??? public? $db_password??? = ''; //數(shù)據(jù)庫密碼??
??? public? $db_name??????? = ''; //數(shù)據(jù)庫名??
??? public? $link?????????? = ''; //數(shù)據(jù)庫連接對象??
??? public? $debug????????? = 1; //是否開啟debug調(diào)試,默認是開啟的??
??? public? $pconnect?????? = 0; //是否開啟長連接,默認是關(guān)閉的??
??? public? $log_file?????? = 'log/';//日志文件目錄??
?
??? /**
???? *初始化信息
???? *@param object
???? **/?
??? public function __construct($config=''){?
??????? if(!is_object($config)){?
??????????? $this->halt('database config is not wrong,please check it!');?
??????? }?
??????? if(!empty($config)){?
??????????? $this->db_host???? = $config->host;?
??????????? $this->db_username = $config->username;?
??????????? $this->db_password = $config->password;?
??????????? $this->db_name???? = $config->dbname;????????
??????? }?
??????? $this->connect();?
??? }?
?????
??? /**
???? * 獲取鏈接
???? * */?
???? public function connect(){?
???????? $connect = $this->pconnect === 1?'mysql_pconnect':'mysql_connect';?
???????? if(!$this->link = @$connect($this->db_host,$this->db_username,$this->db_password)){?
??????????? $this->halt('Database cant not connect!');?
???????? }?
????????? mysql_set_charset('utf8',$this->link);?
????????? mysql_select_db($this->db_name,$this->link);?
???? }?
?
?
???? /**
????? *query
????? *@param string $sql
????? *return boolean?
????? **/?
???? public function query($sql){?
??????? if(!$query = mysql_query($sql,$this->link)){?
???????????? $message = date('Y-m-d H:i:s').'? '.$sql;?
???????????? $this-> write_log($message);?
???????????? $this->halt('SQL error,please check it!',$sql);?
??????? }?
??????? return $query;?
???? }?
?
???? /**
????? *
????? *@param string $sql
????? *@param string $type
????? * mysql_fetch_assoc? mysql_fetch_array? mysql_fetch_row? mysql_affected_rows
????? *@return array
????? */?
???? public function fetch($sql,$type='assoc'){?
??????? $fetch_type = 'mysql_fetch_'.$type;?
??????? $query = $this->query($sql);?
??????? $result = $fetch_type($query);?
??????? $this->free_result($query);?
??????? $this->close();?
??????? return $result;?
???? }?
?
???? /**
????? *@param string $sql
????? *@return array
????? **/?
???? public function dickFetch($sql,$type='assoc'){?
??????? $fetch_type = 'mysql_fetch_'.$type;?
??????? $query = $this->query($sql);?
??????? $rows=array();?
??????? while ($row=$fetch_type($query)) {?
??????????? $rows[]=$row;?
??????? }?
??????? $this->free_result($query);?
??????? $this->close();?
??????? return $rows;?
???? }?
?
???? /**
????? *取得insert 最后一次的ID
????? *@param string $sql
????? **/?
???? public function insert_id(){?
??????? return mysql_insert_id($this->link);?
???? }?
?
???? /**
????? *釋放數(shù)據(jù)庫對象資源
????? **/?
???? public function free_result($query){?
??????? return mysql_free_result($query);?
???? }?
?
?
???? /**
????? *關(guān)閉數(shù)據(jù)庫連接
????? **/?
???? public function close(){?
??????? if($this->pconnect === 0) return mysql_close($this->link);?
???? }?
??????
?
?
??? /**
???? * 整數(shù)安全處理,僅返回大于等于0的整數(shù)
???? *@param int
???? *@return int
???? * */?
??? public function numeric(& $variint){?
??????? if (!isset ($variint))?
??????????? return 0;?
??????? if (!is_numeric($variint))?
??????????? return 0;?
?
??????? //首字符0處理??
??????? $str_len = strlen($variint);?
??????? for ($i = 0; $i
??????????? if ($variint[$i] != '0')?
??????????????? break;?
??????? }?
??????? if ($i > 0 && $variint > 0) {?
??????????? $variint = substr($variint, $i, $str_len);?
??????????? $str_len = strlen($variint);?
??????? }?
?
??????? //數(shù)字安全處理??
??????? if ($str_len > 0) {?
??????????? if (!preg_match("/^[0-9]+$/", $variint)) {?
??????????????? return 0;?
??????????? } else {?
??????????????? $variint = substr($variint, 0, 10);?
??????????????? //兼容MYSQL中INT無符號最大值4294967295??
??????????????? $variint = ($variint > 4294967295) ? 4294967295 : $variint;?
??????????????? return $variint;?
??????????? }?
??????? } else {?
??????????? return 0;?
??????? }?
??? }?
?
??? /**
???? *返回mysql error
???? **/?
??? public function error() {?
??????? return (($this->link) ? mysql_error($this->link) : mysql_error());?
??? }?
?
?
??? /**
???? *返回mysql errno
???? **/?
??? public function errno() {?
??????? return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());?
??? }?
?
??? /**
???? *寫入SQL錯誤日志
???? *@param string
???? *@param string type
???? **/?
??? public function write_log($message='',$type='date'){?
??????? if(empty($message))return false;?
??????? if(!in_array($type, array('date','month')))return false;?
??????? if(!is_dir($this->log_file)){?
??????????? mkdir($this->log_file);?
??????? }?
??????? switch ($type) {?
??????????? case 'month':?
??????????????? $file = $this->log_file.date('Y-m').'.log';?
??????????????? break;?
?????????????
??????????? default:?
??????????????? $file = $this->log_file.date('Y-m-d').'.log';?
??????????????? break;?
??????? }?
??????? if(!file_exists($file)){?
??????????? file_put_contents($file,'');?
??????? }?
??????? if(!is_readable($file)){?
??????????? $this->halt($file.'- 系統(tǒng)無權(quán)限讀操作!');????
??????? }?
??????? if(!is_writable($file)){?
??????????? $this->halt($file.'- 系統(tǒng)無權(quán)限寫操作!');?
??????? }?
??????? $contents = file_get_contents($file);?
??????? $add_message = '? -Error:'.$this->error().'?? -Errno:'.$this->errno();?
??????? file_put_contents($file, $contents.$message.$add_message."\n");?
?????????
??? }?
?
?
??? /**
????? *終止程序
????? *@param str $message
????? *@return print
????? **/?
???? public function halt($message='',$sql=''){?
??????? if($this->debug===1){?
??????????? $error_get_last = error_get_last();?
??????????? if($message) {?
??????????????? $errmsg = "System info: $message\n\n";?
??????????? }?
??????????? $errmsg .= "Time: ".date('Y-m-d H:i:s')."\n";?
??????????? $errmsg .= "Script: ".$error_get_last['file']."\n\n";?
??????????? if($sql) {?
??????????????? $errmsg .= "SQL: ".htmlspecialchars($sql)."\n";?
??????????? }?
??????????? $errmsg .= "Error:? ".$this->error()."\n";?
??????????? $errmsg .= "Errno.:? ".$this->errno();?
?
??????????? echo "\n";?
??????????? echo "
";?
??????????? echo nl2br($errmsg);?
??????????? exit();?
??????? }?
?????????
???? }?
?
???? /**
????? *程序測試打印
????? *@param string
????? *@return print
????? **/?
???? public function prf($param){?
??????? echo '
';?<br> ??????? print_r($param);?<br> ??????? echo '';?
??????? exit;?
???? }?
?
?
}?
#################################################?
####測試程序?
####?
##################################################?
error_reporting(E_ALL);?
header('Content-type:text/html;charset=utf-8');?
date_default_timezone_set('Asia/Shanghai');?
$config = array(?
??? 'host'???? => '192.168.2.1',?
??? 'username' => 'root',?
??? 'password' => '',?
??? 'dbname'?? => 'test',?
??? );?
$db = new Dick_Db((object)$config);?
$db???? ->pconnect = 1;?
$sql = 'SELECT * FROM t1';?
$db->prf($db->dickFetch($sql));?
?
?>?

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)

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

PHP's garbage collection mechanism is based on reference counting, but circular references need to be processed by a periodic circular garbage collector; 1. Reference count releases memory immediately when there is no reference to the variable; 2. Reference reference causes memory to be unable to be automatically released, and it depends on GC to detect and clean it; 3. GC is triggered when the "possible root" zval reaches the threshold or manually calls gc_collect_cycles(); 4. Long-term running PHP applications should monitor gc_status() and call gc_collect_cycles() in time to avoid memory leakage; 5. Best practices include avoiding circular references, using gc_disable() to optimize performance key areas, and dereference objects through the ORM's clear() method.

Bref enables PHP developers to build scalable, cost-effective applications without managing servers. 1.Bref brings PHP to AWSLambda by providing an optimized PHP runtime layer, supports PHP8.3 and other versions, and seamlessly integrates with frameworks such as Laravel and Symfony; 2. The deployment steps include: installing Bref using Composer, configuring serverless.yml to define functions and events, such as HTTP endpoints and Artisan commands; 3. Execute serverlessdeploy command to complete the deployment, automatically configure APIGateway and generate access URLs; 4. For Lambda restrictions, Bref provides solutions.

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

UseaRESTAPItobridgePHPandMLmodelsbyrunningthemodelinPythonviaFlaskorFastAPIandcallingitfromPHPusingcURLorGuzzle.2.RunPythonscriptsdirectlyfromPHPusingexec()orshell_exec()forsimple,low-trafficusecases,thoughthisapproachhassecurityandperformancelimitat

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

Create a seeder file: Use phpartisanmake:seederUserSeeder to generate the seeder class, and insert data through the model factory or database query in the run method; 2. Call other seeder in DatabaseSeeder: register UserSeeder, PostSeeder, etc. in order through $this->call() to ensure the dependency is correct; 3. Run seeder: execute phpartisandb:seed to run all registered seeders, or use phpartisanmigrate:fresh--seed to reset and refill the data; 4
