MySQL database<\/a> and query the student table which we have created earlier.<\/p>\r\n\r\n\r\n\r\nFirst, create a PHP application in the Apache web root directory:<\/p>\r\n\r\n\r\n\r\n
nano \/var\/www\/html\/student.php<\/pre>\r\n\r\n\r\n\r\nAdd the following codes:<\/p>\r\n\r\n\r\n\r\n
<html>\r\n <head>\r\n <title>Using Redis Server with PHP and MySQL<\/title>\r\n <\/head> \r\n <body>\r\n\r\n <h1 align = 'center'>Students' Register<\/h1>\r\n\r\n <table align = 'center' border = '2'> \r\n\r\n <?php \r\n try {\r\n\r\n $data_source = '';\r\n\r\n $redis = new Redis(); \r\n $redis->connect('127.0.0.1', 6379); \r\n\r\n $sql = 'select\r\n student_id,\r\n first_name,\r\n last_name \r\n from student\r\n ';\r\n\r\n $cache_key = md5($sql);\r\n\r\n if ($redis->exists($cache_key)) {\r\n\r\n $data_source = \"Data from Redis Server\";\r\n $data = unserialize($redis->get($cache_key));\r\n\r\n } else {\r\n\r\n $data_source = 'Data from MySQL Database';\r\n\r\n $db_name = 'testdb';\r\n $db_user = 'testuser';\r\n $db_password = 'password';\r\n $db_host = 'localhost';\r\n\r\n $pdo = new PDO('mysql:host=' . $db_host . '; dbname=' . $db_name, $db_user, $db_password);\r\n $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\r\n\r\n $stmt = $pdo->prepare($sql);\r\n $stmt->execute();\r\n $data = []; \r\n\r\n while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { \r\n $data[] = $row; \r\n } \r\n\r\n $redis->set($cache_key, serialize($data)); \r\n $redis->expire($cache_key, 10); \r\n }\r\n\r\n echo \"<tr><td colspan = '3' align = 'center'><h2>$data_source<\/h2><\/td><\/tr>\";\r\n echo \"<tr><th>Student Id<\/th><th>First Name<\/th><th>Last Name<\/th><\/tr>\";\r\n\r\n foreach ($data as $record) {\r\n echo '<tr>';\r\n echo '<td>' . $record['student_id'] . '<\/td>';\r\n echo '<td>' . $record['first_name'] . '<\/td>';\r\n echo '<td>' . $record['last_name'] . '<\/td>'; \r\n echo '<\/tr>'; \r\n } \r\n\r\n\r\n } catch (PDOException $e) {\r\n echo 'Database error. ' . $e->getMessage();\r\n }\r\n ?>\r\n\r\n <\/table>\r\n <\/body>\r\n<\/html>\r\n<\/pre>\r\n\r\n\r\n\r\nSave and close the file when you are finished.<\/p>\r\n\r\n\r\n\r\n
The above application will connect to the MySQL database and cache the data to Redis.<\/p>\r\n\r\n\r\n\r\n