MYSQL PHP PDO Fill table with database data

时间:2015-06-26 09:40:17

标签: php mysql pdo

I want to give out a for every line in my database. It seems that it is working but only returns the first column.

screenshot Note: There are values for the empty fields in database!

$columns = "Ticket, Last_Modified_Date, Requester";

Heres my code:

    function getTicket($columns){
    echo($columns);
    global $db_host, $db_name, $db_user, $db_pass;
    $db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
    $result = $db->prepare("SELECT $columns FROM tickets");
if ($result->execute()){
    echo("<b>Successfully!</b><br><br>");

    $rows = $result->fetchAll(PDO::FETCH_ASSOC);
    $col_names = explode(',', $columns);
foreach($rows as $row){
    echo("<tr>");
foreach($col_names as $col_name){
if (!isset($row[$col_name])){
    continue;
    }
    echo("<td>".$row[$col_name]."</td>");
    }
    echo("</tr>");
        }
    }
else{
    echo("<b>FAILED!</b><br><br>");
    }
    $db = null;
}

2 个答案:

答案 0 :(得分:2)

->fetch() returns only one value of the rows.

Use ->fetchAll() ( PHP Documentation ) if you want to return all of your results.

答案 1 :(得分:0)

There are a couple of issues here, first you should use ->fetchall() which will return ALL the result rows in one hit into an array.

Second you are overwriting your $result statement handle with the row being returned by ->fetch

function getTicket($columns){ 

    global $db_host, $db_name, $db_user, $db_pass;

    $db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");

    $result = $db->prepare("SELECT $columns FROM tickets");

    if ($result->execute()){
        echo("<b>Successfully!</b><br><br>");

        // CHANGES HERE
        $rows = $result->fetchall(PDO::FETCH_ASSOC);

        $col_names = explode(',', $columns);  //make array of csv

        foreach($rows as $row){

            foreach( $col_names as $col_name ) {
                echo '<td>' . $row[$col_name] . '</td>';
            }
        }
    }else{
        echo("<b>FAILED!</b><br><br>");
    }
    $db = null;
}