How to check the connection between mysql and memcached in php

konyu profile image @kon_yu ・2 min read

First things first

We all love PHP, but setting up the middleware is a bit of a pain.
I'm sure I've set it up, but I've got a little snippet to make sure it's all connected.

If PHP and the middleware are configured correctly, the following code will confirm that PHP has access to Mysql and Memcached
If it doesn't work, you're in the middle of a setup gone wrong.

It would be a good idea to check the environment with phpinfo()

Memcached's library uses Memcached, not Memcache, so if you use Memcache, please read the

Create a file for checking and check the operation.

Put the following chack.php in the document root and access it with a browser


  // Database connection check
  // Put the host name, connected user, and password in the argument of mysql_connect, in that order.
  $dbc = mysql_connect('mysql', 'root', 'password');
  if (! $dbc) { dbc = mysql_connect('mysql', 'root', 'password'); if (!
    die('db connection failed<br/>'.mysql_error());
  print('DB connect success! <br/>');

  // selection check in database
  // insert the name of the database to connect to your_database.
  $db_selected = mysql_select_db('your_database', $dbc);

  if (! $db_selected){ { mysql_select_db('your_database', $dbc); if (!
    die('db select failed<br/>'.mysql_error());
  print('db select success! <br/>');

  if (mysql_close($dbc)){
    print('disconnect success! <br/>');

  // memcached connection check
  $m = new Memcached();
  // put memcached host name and port number in addServer's arguments
  $m->addServer('memcached', 11211);

  $m->set('integer', 100);
  $m->set('string', 'string 1234');

? >

If it succeeds, the following will be displayed on the screen

DB connect success!
DB select success!
disconnect success!!!!
string(11) "string 1234"


Editor guide