2

I've got a flexible block of code that allows me to print the results of a query to a simple html table. However, when that table contains a field of type 'datetime', the print() function doesn't work and my loop ends.

In the past, using PHP and MySQL (as opposed to Microsoft SQL Server, which is what I'm using now) printing the date was no problem, so I'm not sure what I'm missing now.

Here's the code:

// $row is the current row.
// $nkeys is the array of (String) keys that correspond to columns in the table.
do {
    print ("<tr>\n");
    foreach($nkeys as $k) {
        echo ("<td>$row[$k]</td>");
    } 
    print ("</tr>\n");
} while ($row = sqlsrv_fetch_array($stmt));

Is there a special function other than print() or echo that will properly print the date?

4 Answers 4

4

The SQLSRV extension returns DateTime objects. Just format it to your liking:

if( !is_null($row[$k]) ){
    echo $row[$k]->format('r');
}

In the procedural interface you are using you can also disable the feature by providing a ReturnDatesAsStrings connection option (this option is not available in the PDO interface) but there's normally no reason to do so.

Sign up to request clarification or add additional context in comments.

Comments

1

Very important to have this in your connection string when using date fields in jqGrid.

"ReturnDatesAsStrings"=>true

Great stuff, thanks Mrigesh !

Comments

0

When using SQLSRV, you can't use something like:

date('d/m/y', strtotime($row['ActivityDate']))

Instead, you have to use:

date_format($row['ActivityDate'], 'd/m/y')

Comments

0

Although you can change the behavior of returning Date Time Object by SQLSRV. This can be done by keeping ReturnDatesAsStrings TRUE in connection option. Changing connection code like below will do the trick:

$link = sqlsrv_connect( $db_server_name, array( "UID"=>$db_user,
            "PWD"=>$db_pass,
            "Database"=>$db_name,
            "ReturnDatesAsStrings"=>true
          ));

With this your existing code echo ("<td>$row[$k]</td>"); will return the values without any other workaround. Consider this if you have got many spots to apply "->format('r')".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.