ΪʲôҪʹÓà mysqli_close()?

ʱ¼ä£º2023-03-06
±¾ÎĽéÉÜÁËΪʲôҪʹÓà mysqli_close()?µÄ´¦Àí·½·¨£¬¶Ô´ó¼Ò½â¾öÎÊÌâ¾ßÓÐÒ»¶¨µÄ²Î¿¼¼ÛÖµ£¬ÐèÒªµÄÅóÓÑÃÇÏÂÃæËæןú°æÍøµÄС±àÀ´Ò»Æðѧϰ°É£¡

ÎÊÌâÃèÊö

ÓÐʲôÀíÓÉÈÃÎÒÔÚ²éѯ֮ºó»ò½Å±¾½áÊøʱ¹Ø±ÕÁ¬½ÓÂð?

Is there any reason why I should close the connection after a query or at the end of the script?

×ö/²»×öÓÐʲôºÃ´¦?

ÍƼö´ð°¸

Á¬½Ó(Èç¹û²»Êdz־õÄ) ×ÜÊÇÔڽű¾½áÊøʱ¹Ø±Õ£¬ËùÒÔ£¬ÀíÂÛÉÏ£¬Äã²»»áÐèÒª×Ô¼º¹Ø±Õ.

The connection (if not persistent) is always closed at the end of the script, so, in theory, you don't need to close it yourself.

²»¹ý£¬Èç¹ûÄúµÄ PHP ½Å±¾ÐèÒª´óÁ¿Ê±¼äÀ´Ö´ÐУ¬ÄÇôµ±Äú²»ÔÙÐèÒª¶ÔÊý¾Ý¿âÖ´ÐÐÈκÎÇëÇóʱ¹Ø±ÕÁ¬½ÓÊǸöºÃÖ÷Ò⡪¡ªÖÁÉÙ£¬Èç¹û³¤Ê±¼äµÄ¼ÆËãÊÇÔÚÖ®ºóÍê³ÉµÄ²éѯ.

Still, if your PHP script takes lots of time to execute, it's a good idea to close the connection when you don't have to do any request to the database anymore -- at least, if the long calculations are done after the queries.

Èç¹ûÄúµÄÓ¦ÓóÌÐò²¿ÊðÔÚ¹²ÏíÖ÷»úÉÏ£¬ÔòÓÈÆäÈç´Ë:ÄúµÄÓû§ÕÊ»§Í¨³£Ö»ÄÜͬʱ´ò¿ª¼¸¸öÁ¬½Ó.(ÔÚ¹²ÏíÖ÷»úÉÏ£¬Í¬Ê±´ò¿ªµÄÁ¬½ÓÊýÁ¿¿ÉÄܺÜÉÙ£»ÔÚ˽ÈË·þÎñÆ÷ÉÏͨ³£¸ü´ó).

This is especially true if your application is deployed on a shared hosting : your user account can generally only have a few connections opened at the same time. (That number of simultaneous opened connections can be pretty small on shared hosting ; it's generally bigger on private servers).


ÎÒÃǾ­³£²»¹Ø±Õ×Ô¼ºµÄÁªÏµµÄÔ­ÒòÊÇ:


The reason we often don't close connections ourselfves is :

  • ÎÒÃÇͨ³£²»ÖªµÀºÎʱÍê³ÉÁËËùÓвéѯ¡ª¡ª¶ÔÓÚÓÉÐí¶àС¿é"×é³ÉµÄÒ³ÃæÓÈÆäÈç´Ë£»Ã¿Ò»¸ö¶¼ÊǶÀÁ¢ÓÚÆäËûµÄ£¬²¢ÇÒ¿ÉÒÔ×Ô¼º½øÐвéѯ£»ÄÇô£¬ÎÒÃÇʲôʱºò¿ÉÒԹرÕÁ¬½Ó?
  • ÍøÒ³µÄÉú³ÉËÙ¶Èͨ³£·Ç³£¿ì£¬Òò´ËÎÒÃDz»±Øµ£ÐĹرÕÓëÊý¾Ý¿âµÄÁ¬½Ó.

Õâƪ¹ØÓÚΪʲôҪʹÓà mysqli_close()?µÄÎÄÕ¾ͽéÉܵ½ÕâÁË£¬Ï£ÍûÎÒÃÇÍƼöµÄ´ð°¸¶Ô´ó¼ÒÓÐËù°ïÖú£¬Ò²Ï£Íû´ó¼Ò¶à¶àÖ§³Ö¸ú°æÍø£¡

ÉÏһƪ£ºmysql & µÄÇø±ðmysqli ÏÂһƪ£ºË¢Ð mysqli_multi_query() µÄËÙ¶È/×î¼Ñʵ¼ù

Ïà¹ØÎÄÕÂ