本文分享一个好用的php与mysql操作类,此mysql类与其它类的不同在于,可以设置表的读、写锁。有需要的朋友参考下吧。
分享一个php与mysql操作类,代码: <?php /** * mysql操作类 * by bbs.it-home.org */ // 定义常量 /** * 是否开启调试模式 */ define("DEBUG", FALSE); /** * 以下变量不要改动 */ /** * 设定表的读锁 */ define("LOCKED_FOR_READ", "READ"); /** * 设定表的写锁 */ define("LOCKED_FOR_WRITE", "WRITE"); /** * HOWTO */ class mySQL { /** * The connection resource id * * @var object */ var $connection; /** * The selected database * * @var object */ var $selectedDb; /** * The result from a select-query * * @var object */ var $result; /** * Flag that tells if you are connected to the database or not * * @var boolean */ var $isConnected; /** * Flag that tells if you the tables are locked or not * * @var boolean */ var $isLocked; /** *This will indicate what querytype the last query was * * @var string */ var $queryType; /** * This is the constructor of this mysql class. * It creates a connection to the database, and if possible it sets the database to * You can specify if you want to use persistant connections or not. * * @param string The host to the mySQL server * @param string The username you use to log on to the mySQL server * @param string The password you use to log on to the mySQL server * @param string The name of the database you wish to use * @param boolean TRUE if you want to use persistant connections. Default is TRUE * @return boolean TRUE when connection was successfull * @access public */ function mySQL($sHost, $sUser, $sPassword, $sDatabase="", $bPersistant=TRUE) { $conFunc = ""; if(!defined("DEBUG")) { define("DEBUG", FALSE); } if($this->getConnected()) { $this->closeConnection(); } if($this->connection = ($bPersistant ? mysql_pconnect($sHost, $sUser, $sPassword) : mysql_connect($sHost, $sUser, $sPassword))) { $this->setConnected(TRUE); if($sDatabase) { $this->setDb($sDatabase); } return TRUE; } else { $this->setConnected(FALSE); return FALSE; } } /** * This is the destructor of this class. It frees the result of a query, * it unlocks all locked tables and close the connection to the database * It does not return anything at all, so you will not know if it was sauccessfull * * @access public */ function _mySQL() { if($this->result) { $this->freeResult(); } if($this->getLocked()) { $this->unlock(); } if($this->getConnected()) { $this->closeConnection(); } } /** * This function frees the result from a query if there is any result. * * @access public */ function freeResult() { if($this->result) { @mysql_free_result($this->result); } } /** * This function executes a query to the database. * The function does not return the result of the query, you must call the * function getQueryResult() to fetch the result * * @param string The query-string to execute * @return boolean TRUE if the query was successfull * @access public */ function query($query) { if(strlen(trim($query)) == 0) { $this->printError("No query got in function query()"); return FALSE; } if(!$this->getConnected()) { $this->printError("Not connected in function query()"); return FALSE; } $queryType = substr(trim($query), 0, strpos($query, " ")); $this->setQueryType($queryType); $this->result = mysql_query($query, $this->connection); if($this->result) { return TRUE; } return FALSE; } /** * Sets the querytype of the last query executed * For example it can be SELECT, UPDATE, DELETE etc. * * @access private */ function setQueryType($type) { $this->queryType = strtoupper($type); } /** * Returns the querytype * * @return string * @access private */ function getQueryType() { return $this->queryType; } /** * This function returns number of rows got when executing a query * * @return mixed FALSE if there is no query-result. * If the queryType is SELECT then it will use the function MYSQL_NUM_ROWS * Otherwise it uses the MYSQL_AFFECTED_ROWS * @access public */ function getNumRows() { if($this->result) { if(DEBUG==TRUE) { print("<font style=\"background-color: red\">".$this->getQueryType()."</font><br>"); } return mysql_affected_rows($this->connection); } return FALSE; } /** * The function returns the result from a call to the query() function * * @return object * @access public */ function getQueryResult() { return $this->result; } /** * This function returns the query result as an array for each row in the query result * * @return array * @access public */ function fetchArray() { if($this->result) { return mysql_fetch_array($this->result); } return FALSE; } /** * This function returns the query result as an object for each row in the query result * * @return object * @access public */ function fetchObject() { if($this->result) { return mysql_fetch_object($this->result); } return FALSE; } /** * This function returns the query result as an array for each row in the query result * * @return array * @access public */ function fetchRow() { if($this->result) { return mysql_fetch_row($this->result); } return FALSE; } /** * This function sets the database * * @return boolean TRUE if the database was set * @access public */ function setDb($sDatabase) { if(!$this->getConnected()) { $this->printError("Not connected in function setDb()"); return FALSE; } if($this->selectedDb = mysql_select_db($sDatabase, $this->connection)) { return TRUE; } return FALSE; } /** * This function returns a flag so you can see if you are connected to the database * or not * * @return boolean TRUE when connected to the database * @access public */ function getConnected() { return $this->isConnected; } /** * This function sets the flag so you can see if you are connected to the database * * @param $bStatus The status of the connection. TRUE if you are connected, * FALSE if you are not * @access public */ function setConnected($bStatus) { $this->isConnected = $bStatus; } /** * The function unlocks tables if there are locked tables and the closes the * connection to the database. * * @access public */ function closeConnection() { if($this->getLocked()) { $this->unlock(); } if($this->getConnected()) { mysql_close($this->connection); $this->setConnected(FALSE); } } /** * Unlocks all tables that are locked * * @access public */ function unlock() { if(!$this->getConnected()) { $this->setLocked(FALSE); } if($this->getLocked()) { $this->query("UNLOCK TABLES"); $this->setLocked(FALSE); } } /** * This function locks the table(s) that you specify * The type of lock must be specified at the end of the string. * * @param string a string containing the table(s) to lock, * as well as the type of lock to use (READ or WRITE) * at the end of the string * @return boolean TRUE if the tables was successfully locked * @access private */ function lock($sCommand) { if($this->query("LOCK TABLE ".$sCommand)) { $this->setLocked(TRUE); return TRUE; } $this->setLocked(FALSE); return FALSE; } /** * This functions sets read lock to specified table(s) * * @param string a string containing the table(s) to read-lock * @return boolean TRUE on success */ function setReadLock($sTable) { return $this->lock($sTable." ".LOCKED_FOR_READ); } /** * This functions sets write lock to specified table(s) * * @param string a string containing the table(s) to read-lock * @return boolean TRUE on success */ function setWriteLock($sTable) { return $this->lock($sTable." ".LOCKED_FOR_WRITE); } /** * Sets the flag that indicates if there is any tables locked * * @param boolean The flag that will indicate the lock. TRUE if locked */ function setLocked($bStatus) { $this->isLocked = $bStatus; } /** * Returns TRUE if there is any locked tables * * @return boolean TRUE if there are locked tables */ function getLocked() { return $this->isLocked; } /** * Prints an error to the screen. Can be used to kill the application * * @param string The text to display * @param boolean TRUE if you want to kill the application. Default is FALSE */ function printError($text, $killApp=FALSE) { if($text) { print("<b>Error</b><br />".$text); } if($killApp) { exit(); } } /** * Display any mysql-error * * @return mixed String with the error if there is any error. * Otherwise it returns FALSE */ function getMysqlError() { if(mysql_error()) { return "<br /><b>Mysql Error Number ".mysql_errno()."</b><br />".mysql_error(); } return FALSE; } } ?> |

PHP는 현대적인 프로그래밍, 특히 웹 개발 분야에서 강력하고 널리 사용되는 도구로 남아 있습니다. 1) PHP는 사용하기 쉽고 데이터베이스와 완벽하게 통합되며 많은 개발자에게 가장 먼저 선택됩니다. 2) 동적 컨텐츠 생성 및 객체 지향 프로그래밍을 지원하여 웹 사이트를 신속하게 작성하고 유지 관리하는 데 적합합니다. 3) 데이터베이스 쿼리를 캐싱하고 최적화함으로써 PHP의 성능을 향상시킬 수 있으며, 광범위한 커뮤니티와 풍부한 생태계는 오늘날의 기술 스택에 여전히 중요합니다.

PHP에서는 약한 참조가 약한 회의 클래스를 통해 구현되며 쓰레기 수집가가 물체를 되 찾는 것을 방해하지 않습니다. 약한 참조는 캐싱 시스템 및 이벤트 리스너와 같은 시나리오에 적합합니다. 물체의 생존을 보장 할 수 없으며 쓰레기 수집이 지연 될 수 있음에 주목해야합니다.

\ _ \ _ 호출 메소드를 사용하면 객체를 함수처럼 호출 할 수 있습니다. 1. 객체를 호출 할 수 있도록 메소드를 호출하는 \ _ \ _ 정의하십시오. 2. $ obj (...) 구문을 사용할 때 PHP는 \ _ \ _ invoke 메소드를 실행합니다. 3. 로깅 및 계산기, 코드 유연성 및 가독성 향상과 같은 시나리오에 적합합니다.

섬유는 PHP8.1에 도입되어 동시 처리 기능을 향상시켰다. 1) 섬유는 코 루틴과 유사한 가벼운 동시성 모델입니다. 2) 개발자는 작업의 실행 흐름을 수동으로 제어 할 수 있으며 I/O 집약적 작업을 처리하는 데 적합합니다. 3) 섬유를 사용하면보다 효율적이고 반응이 좋은 코드를 작성할 수 있습니다.

PHP 커뮤니티는 개발자 성장을 돕기 위해 풍부한 자원과 지원을 제공합니다. 1) 자료에는 공식 문서, 튜토리얼, 블로그 및 Laravel 및 Symfony와 같은 오픈 소스 프로젝트가 포함됩니다. 2) 지원은 StackoverFlow, Reddit 및 Slack 채널을 통해 얻을 수 있습니다. 3) RFC에 따라 개발 동향을 배울 수 있습니다. 4) 적극적인 참여, 코드에 대한 기여 및 학습 공유를 통해 커뮤니티에 통합 될 수 있습니다.

PHP와 Python은 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1.PHP는 간단한 구문과 높은 실행 효율로 웹 개발에 적합합니다. 2. Python은 간결한 구문 및 풍부한 라이브러리를 갖춘 데이터 과학 및 기계 학습에 적합합니다.

PHP는 죽지 않고 끊임없이 적응하고 진화합니다. 1) PHP는 1994 년부터 새로운 기술 트렌드에 적응하기 위해 여러 버전 반복을 겪었습니다. 2) 현재 전자 상거래, 컨텐츠 관리 시스템 및 기타 분야에서 널리 사용됩니다. 3) PHP8은 성능과 현대화를 개선하기 위해 JIT 컴파일러 및 기타 기능을 소개합니다. 4) Opcache를 사용하고 PSR-12 표준을 따라 성능 및 코드 품질을 최적화하십시오.

PHP의 미래는 새로운 기술 트렌드에 적응하고 혁신적인 기능을 도입함으로써 달성 될 것입니다. 1) 클라우드 컴퓨팅, 컨테이너화 및 마이크로 서비스 아키텍처에 적응, Docker 및 Kubernetes 지원; 2) 성능 및 데이터 처리 효율을 향상시키기 위해 JIT 컴파일러 및 열거 유형을 도입합니다. 3) 지속적으로 성능을 최적화하고 모범 사례를 홍보합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

WebStorm Mac 버전
유용한 JavaScript 개발 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기
