如何在php中使用SQL查询显示来自DB2数据库的数据

时间:2017-06-22 18:42:20

标签: php html db2

我正在使用php为我的db2数据库构建一个简单的前端Web应用程序。此php查询连接到数据库并从我选择的表中提取数据。我正在尝试将我的数据插入到html表中以更好地显示它(由于“db2_fetch_array”函数,行现在以数组格式显示。如何将我的数据放入html表?我的php代码是下面,我应该添加什么?我能找到的大多数问题只涉及mySQL,并且没有和我一样的规范。

<html>
<head><title>DB Testing</title></head>
<body>

<?php
//db2 express c (v10.5)
$database = "database";
$user = "db";
$password = "password";

$conn = db2_connect($database, $user, $password);

if($conn) {
echo "DB2 Connection succeeded.<br/>";
}
    else{
    exit("failed".db2_conn_errormsg());
    }


$sql = "select 'JUNK', apple, banana, orange, cake, grapes, egg from 
kitchen";

//db2_execute executes a sql statement that was prepared by db2_prepare
if($stmt){
    $result = db2_execute($stmt);
    if(!$result){
        echo "exec errormsg: " .db2_stmt_errormsg($stmt);
        }
    echo '<table>';
while($row = db2_fetch_array($stmt)) {
    echo '<tr>';
    echo '<td>' . $row['apple'] . '</td>';
    echo '<td>' . $row['banana'] . '</td>';
    echo '<td>' . $row['orange'] . '</td>';
    echo '<td>' . $row['cake'] . '</td>';
    echo '<td>' . $row['grapes'] . '</td>';
    echo '<td>' . $row['egg'] . '</td>';
    echo '</tr>';   
}
echo '</table>';
}else {
echo "exec errormsg: ".db2_stmt_errormsg($stmt);
}
db2_close($conn);

?>
<?php
function print_r2($val){
        echo '<table>';
    print_r($val);
    echo '</table>';
    }

    ?> 

</body>
</html>

1 个答案:

答案 0 :(得分:0)

我假设语法错误:

$sql = "select rows from table ;

是您更改查询以询问此问题的结果。无论如何,修复它,查询字符串不会关闭。另外,我猜你没有一个名为&#34; rows&#34;在表格中,您需要列出所需的列。

您已经拥有了正确的循环,只需使用表格结构更改<pre>标记:

echo '<table>';
while($row = db2_fetch_array($stmt)) {
    echo '<tr>';
    echo '<td>' . $row['columnName'] . '</td>';
    // repeat with your other columns
    echo '</tr>';
}
echo '</table>';