douli1306 2015-11-06 18:53
浏览 23
已采纳

在PHP 5.x中是否有任何简单的方法来回显RecordSet上的任何类型的数据?

So this is it.

I wrote a SQL statement dumb as duck, like:

SELECT * FROM table

Basically I want:

  1. Do a generic SELECT statement;
  2. Loop through the Resulset;
  3. Print the metadata "name" as Table Headers.
  4. Loop through Resultset again;
  5. Print each record as table row.
  6. Print each field as table column.
  7. How to test the data, in the field so I can properly echo this data as string? I'm not sure if I made myself clear.

I can't know what data will be returned form the statements, previously. This is motivated after trying print DateTime fields, and getting an error.

This is my PHP code:

    $sql = "SELECT * FROM client";      

    $stmt = sqlsrv_query($conn, $sql);    

    if( $stmt === false) 
    {
        die( print_r( sqlsrv_errors(), true));
    }

    $num_fields = sqlsrv_num_fields($stmt);

    echo '<table class="table table-striped table-bordered">';
    // Output Headers - In SQL Server

    echo '<tr  style="font-size:12px">';
    foreach( sqlsrv_field_metadata( $stmt ) as $fieldMetadata ) 
    {
        foreach( $fieldMetadata as $name => $value) 
        {
            if ($name == "Name"){
                echo  "<td><strong>" . "$value" . "</td></strong>";
            }
        }

    }
    echo "</tr>";

    // Output fields data, after fetch new row.
    while ( sqlsrv_fetch ( $stmt ) ) 
    {
        // \echo '<tr class="small"  style="font-size:10px">';
        echo '<tr class="small">';
        for ($i = 0; $i < $num_fields; $i++)
        {
            echo '<td class="text-nowrap">';
            print_r (sqlsrv_get_field($stmt, $i));
            echo "</td>";
        }
        echo "</tr>";
    }
    echo "</table>";

Please, correct me about any bad practice, or stupid coding... I'm a complete newbie here.

  • 写回答

1条回答 默认 最新

  • dqyz48470 2015-11-06 19:41
    关注

    You could specify the data type of the result value, and choose the string data type, as follows:

    print_r (sqlsrv_get_field($stmt, $i, SQLSRV_PHPTYPE_STRING( SQLSRV_ENC_CHAR)));
    

    Alternatively, instead of calling sqlsrv_fetch and sqlsrv_get_field, use sqlsrv_fetch_array as that automatically converts all retrieved data to string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题