weixin_43190055 2019-05-29 22:38 采纳率: 0%
浏览 199

PHP+SQL server查询怎么放进表格里,调整格式?

PHP连接SQL server2012,我通过代码可以通过id查询到数据库信息,但是格式很乱,怎么调整格式,把信息统一放到一张表格里?查询代码如下:

<?php

    $id = @$_GET['id'] ? $_GET['id'] : '';

    class sql{
private $serverName = "DESKTOP-9BM0PFR"; //sql server链接实例名
private $connectionInfo = array("UID"=>"sa","PWD"=>"123","Database"=>"PHP"); //配置用户名,密码,数据库
public $sql = "select *from test where id=''"; //默认的sql语句
public $result;
public $conn = '';
    public function __construct( $name ='' , $user ='' , $pwd ='' ,$db = '' ){
if( $name ){
$this->serverName = $name;
}
if( $user ){
$this->connection['UID'] = $user;
}
if( $pwd ){
$this->connection['PWD'] = $pwd;
}
if( $db ){
$this->connection['Database'] = $db;
}

//connect to sqlserver
if( !$this->conn ){
$this->conn = sqlsrv_connect( $this->serverName, $this->connectionInfo)
or die( sqlsrv_errors() );
}
}

public function doQuery( $sql ){
if(!$this->conn){
return " sorry ,can't to link server" ;
}
if( $sql ){
$this->sql = $sql ;
}
$this->result = sqlsrv_query($this->conn,$this->sql) ;
return $this->result;
}

public function close(){
if($this->conn){
sqlsrv_close ( $this->conn ) ;
}
}
}
//phpinfo();

$server = new sql();
$sql = "select *from test where id='$id' "; //sql语句写在这
$result = $server->doQuery( $sql ); //查询返回的句柄
$output = '';
if ( ! is_string( $result )){
while ( $re = sqlsrv_fetch_array ( $result )){ //sqlsrv_fetch_array 通过查询结果句柄获取查询结果
//$output[] = $re; //打印查询结果
var_dump( $re ) ;
}
}else{

     echo $result;
}


?>
运行结果如下:![图片说明](https://img-ask.csdn.net/upload/201905/29/1559141125_985782.png)
  • 写回答

1条回答 默认 最新

  • 憧憬blog 2023-03-15 07:15
    关注

    首先,你可以使用HTML中的表格标签 <table> 来把查询结果放入表格中,具体的代码如下:

    $output = '<table>';
    $output .= '<tr><th>id</th><th>name</th><th>age</th></tr>'; //表格头部
    
    if ( ! is_string( $result )){
        while ( $re = sqlsrv_fetch_array ( $result )){ 
            $output .= '<tr>';
            $output .= '<td>'. $re['id'].'</td>';
            $output .= '<td>'. $re['name'].'</td>';
            $output .= '<td>'. $re['age'].'</td>';
            $output .= '</tr>';
        }
    }else{
         $output .= '<tr><td colspan="3">'. $result .'</td></tr>'; //如果有错误,提示错误信息
    }
    $output .= '</table>';
    
    echo $output;
    

    上述代码中,使用了字符串拼接符号 . 来拼接表格中的各个元素。<tr> 表示行,<td> 表示列,<th> 表示表格头部。在拼接元素时,还使用了结果集中的字段名,即 $re['字段名'],如 $re['id'] 即表示查询结果中的 id 列。

    最后,把拼接好的表格 $output 打印输出即可。

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!