Monday, February 21, 2011

How to get current localtime using Mysql and PHP?

I read from mysql website, I execute this:

SELECT CURTIME()

But then how to get the value? Using mysql_fetch_assoc()??

From stackoverflow
  • SELECT CURTIME() as time_now
    

    *EDIT

    $conn = mysql_connect("localhost", "mysql_user", "mysql_password");
    $sql = "SELECT CURTIME() as time_now";
    $result = mysql_query($sql);
    while ($row = mysql_fetch_assoc($result)) {
        echo $row["time_now"];
    }
    
    xiasue1982 : how to get the result??
    halocursed : Are you using classes? if not check greg's answer
  • Yes, you execute it as a normal query. You might want to alias the column to a nicer name:

    $data = mysql_query('SELECT CURTIME() AS the_time');
    $row = mysql_fetch_assoc($data);
    $theTime = $row['the_time'];
    

    It's going to be more efficient to get the time through PHP rather than doing an expensive SQL query.

    You can use the date() function:

    $theTime = date('H:i:s');
    

0 comments:

Post a Comment