search
HomeBackend DevelopmentPHP Tutorial memcached 怎么使用

memcached 如何使用?
我在做一个在线答题系统,在同一界面刷新题目,每点击下一题刷新一题,
过程:1从数据库中取题(取完之后$db->close()),2点下一题。重复1,2两步直到题目答完。
这样的话就相当于每取出一个题都要连接一次数据库,经同学建议可以把数据存到memcached中
这样就可以减少对数据库的连接次数。
我想问的是在什么位置把memcached类放进去才能达到效果?
比如取第一题
首先我要连接数据库
然后把题取出来
while($row=mysql_fetch_array($result){
  $question[]=$row[question];
}//到这里为止所有的题目就都取出来了
$mem = new Memcache; //我把memcache类放在数据库取值的后面了
$mem->connect("127.0.0.1", 11211);
$mem->set("key",$question);
$question=$mem->get("key");
$db->close();
然后问题来了
1.怎么样才能保证只是第一次取题的时候连接数据库并把所有的数据都赋给memcache类中的$question像我这样写的话虽然把值赋给了memcache,但是点击下一题时,仍然相当于连接了数据库.
2.在读出第一题后我就把数据库连接的类给注释掉了,我想的是因为读第一题的时候因为已经把题目赋给缓存了,所以不需要数据库的连接了。但是点下一题的时候什么都没读出来,那么我读第一题时给缓存赋的值哪里去了?难道页面刷新会使缓存中的值丢失吗?
我觉得肯定是我使用memcached方法不正确,这个类应该放在什么位置才能减少数据库的连接次数,希望使用过的人给我一些思路

------解决方案--------------------
你这上面的代码等于每次都读数据库,然后把值写入缓存,应该在读数据库之前if(false == $mem->get("key")),这样当key存在的时候就不会连接数据库重新设置set了
------解决方案--------------------
这个次序

PHP code
$mem = new Memcache; 
$mem->connect("127.0.0.1", 11211);
if(! $mem->get("key")) {
  //数据库连接查询的代码
  while($row=mysql_fetch_array($result){
    $question[]=$row[question];
  }//到这里为止所有的题目就都取出来了
  $mem->set("key",$question);
}
$question=$mem->get("key"); <div class="clear">
                 
              
              
        
            </div>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use