DEV Community

@kon_yu
@kon_yu

Posted on

How to check the connection between mysql and memcached in php

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()

Caution.
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

<html>
  <body>.
<?php

  // 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');

  var_dump($m->get('integer'));
  print('<br/>');
  var_dump($m->get('string'));
? >
  </body>.
</html>
Enter fullscreen mode Exit fullscreen mode

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

DB connect success!
DB select success!
disconnect success!!!!
int(100) 
string(11) "string 1234"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)