Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

RSS Latest posts from my personal blog


Most viewed posts


Subscribe to RSS feed


Display MySQL server uptime in PHP

Stanislav KhromovStanislav Khromov

With this snippet you can print the uptime of a MySQL server from a PHP script. It uses PDO to make the connection.

If you know a simpler way to do this, feel free to post a comment!

try
{                               
    $dbh = new PDO('mysql:host=localhost;dbname=database_name', 'user', 'password');
    foreach($dbh->query("SHOW GLOBAL STATUS LIKE 'Uptime'") as $row)
    {
        echo ' MySQL server OK, uptime ';   
        echo ($row['Value'] >= 31557000) ? ' >365 days' : (gmdate("z", ($row['Value'])) . ' days, ' . gmdate("H:i", $row['Value']));                        
    }
}
catch (PDOException $e)
{
    print "MySQL server error: <br/> " . $e->getMessage();
}

The result will look something like this:

15 days, 04:38

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 2
  • matt
    Posted on

    matt matt

    Reply Author

    Hi, how to add hours, minutes and seconds? eg. working time server: 2d 8h 47m 22s.