doulei3488 2017-06-22 18:42
浏览 140
已采纳

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

I'm using php to build a simple front end web application to my db2 database. This php query connects to the database and pulls the data from my selected table. I'm trying to insert my data into an html table to display it better (the rows are showing up in array formatting right now due to the "db2_fetch_array" function. How do I put my data into an html table? My php code is below, what should I add? Most questions I could find only dealt with mySQL and didn't have the same specification as I do.

<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条回答 默认 最新

  • dongshao8471 2017-06-22 20:08
    关注

    I assume the syntax error here:

    $sql = "select rows from table ;
    

    is the result of you changing your query to ask this question. In any event, fix it, the query string is not closed. Also, I guess you don't have a field named "rows" in your table, you need to list the columns you want.

    You already have the right loop, just change the <pre> tags with a table structure:

    echo '<table>';
    while($row = db2_fetch_array($stmt)) {
        echo '<tr>';
        echo '<td>' . $row['columnName'] . '</td>';
        // repeat with your other columns
        echo '</tr>';
    }
    echo '</table>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?