繁体   English   中英

MySQL PHP PDO:从请求中获取表格及其大小

[英]MySQL PHP PDO : getting the table AND its size from a request

我在 PHP 脚本中有几个函数:

    // Database connexion
    function connexion_base() 
    {
        try
        {
            $bdd = new PDO('mysql:host=localhost;dbname=WORLD',
                       'me','S3cr3T');
        }
        catch (Exception $e)
        {
            die('Erreur : '.$e->getMessage());
        }
        return $bdd;
    }

    // Returns the names of the columns
    function column_names($Table) 
    {
        $nb_cols = $Table->columnCount();
        $cols = array();
        for ($i = 0; $i < $nb_cols; $i++)
        {
            $col = $Table->getColumnMeta($i);
            $cols[] = $col['name'];
        }
        return $cols;
    }

    // Prints the body of the table
    function print_table($Table,$Cols) 
    {
        while ($datas = $Table->fetch()) 
        {
            echo '<tr>';
            foreach ($Cols as $element)
            {
                echo '<td>'.$datas[$element].'</td>';
            }
        }
    }

    // Prints the result of request $Request (string) from database $Bdd
    function print_request($Base,$Request)
    {
        $result = $Bdd->query($Requete);
        $cols = column_names($resultat);
        // Printing numer of rows of the result
        // echo '<p>Number of lines in the answer : '.$nb_lignes.'</p>';
        // Head of the table
        echo '<table> <tr>';
        foreach ($cols as $element)
        {
            echo '<th>'.$element.'</th>';
        }
        // End head of the table
        // Printing each line of the table
        write_table($result,$cols);
        // Fin de la table
        echo '</table>';
    }
}

问题是:

  1. 我的代码正确吗? 它有效,但也许我对使用 PDO(和/或 PHP、MySQL ......)没有正确的感觉
  2. 我想在结果页面中的表格前添加一行,指示请求给出的结果数; 我不知道该怎么做。

有什么帮助吗?

要添加一行,您可以在th之后或write_table之后执行<tr><td colspan="{$nb_cols}">{$result->rowCount()}</td></tr>

请注意变量中的拼写错误( $resultat -> $result ),以便它们都相同。 Php 不区分大小写,但我建议不要依赖它来避免混淆,不要混合相同的变量名但使用不同的 styles。

挑剔的注意事项:请 output </tr>在每个循环之后,即使浏览器能够找到出路

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM