php - PHP:如何使用MySQLi在每个HTML表行中显示多个MySQL表记录

标签 php html css mysql database

我想在php中显示mysql数据库中的一行元素。我已经做到了,但是我的数据出现在一个长长的专栏里。我希望每一个新元素都一个接一个地出现。
这是我的截图。我希望第一个在第二个旁边:
https://www.dropbox.com/s/2y3g0n7hqrjp8oz/Capture.PNG?dl=0
这是我的代码:

    <?php
    require_once 'core/init.php';
    include 'includes/navigation.php';

    $sql = "SELECT * FROM interviews WHERE featured = 1";
    $featured = $db->query($sql);


    <html>

enter code here
enter code here
    <link href="http://localhost/menu/css/academy.css" rel="stylesheet" `enter code here`type="text/css" />

    <?php while($product = mysqli_fetch_assoc($featured)) : ?>
    <table>
    <tr>
        <th>
        <div id="element1"></div>
        <div id="content1">

            <img src="<?= $product['image']; ?>" alt="<?= $product['title']; ?>">
            <h4><?= $product['title']; ?></h4>
            <hr>
            <p class="description"><?= $product['description']; ?></p>

    <!--------BUTTON 3-------->
    <div id="hovers">
        <a href="#" class="button">
            <span class="contentbut"> Read More</span>
        </a>
    </div>
    </th>
</tr>
    </table>    
    <?php endwhile; ?>      
    </div>
</div>

求求你,救命。
谢谢您!

最佳答案

介绍
注意:此答案详细说明了如何创建多记录到一行的排列。但是,可以更改此答案以提供一条记录到一行的排列。
分离关注点有助于编写更干净的代码。分离关注点将使维护代码更容易。干净的代码是松散耦合的,没有嵌入依赖项的负担。干净代码在函数签名和类构造函数中标识其依赖关系,期望这些需求将在外部得到满足。干净的代码具有紧密的内聚性。这意味着函数/方法只有一个任务,类只有一个目标。干净的代码通常反映在已被分解和细化的任务中(但并不总是如此)。干净的代码是我追求的理想,但没有人是完美的。
试着想办法从html文件中获取尽可能多的sql和php。插值变量和显示函数的返回结果只能使您的html更易于阅读。好的html结构也很重要。
根据sql查询的结果动态构建<table>的任务很有可能被分解。最终,您可能会决定使用css和div来进行样式和响应。这段代码可以被修改来实现这一点(毕竟,您只需要将盒子成行地堆叠起来)。
最后,创建一个oop类(使用自定义名称空间)对于模块化代码和将绝大多数符号(变量名等)从全局名称空间中取出是非常有用的。
开始之前:php.ini:include_path
是否要为项目设置逻辑目录体系结构?
include_path内设置php.ini
如果在php.ini中搜索include_path设置,则可以将其设置为一个目录或任何适当目录组。这样,您就可以按您所需的方式在目录中排列文件,并且您的includeinclude_oncerequirerequire_once语句仍然可以找到要导入的文件。您不必键入绝对路径(如/dir/dir/file.php)或相对路径(如../../core/database.php)。在这两种情况下,都可以指定文件名。
例子:

include 'file.php';     //Finds the file if it is in the include_path.
require 'database.php'; //Finds the file if it is in the include_path.

注意:将库文件和其他纯php编码文件(等等)放在webroot或任何可公开访问的目录之外。使它们在逻辑上高于webroot。设置include_path以便您不必一直这样做。
任务
1)首先,创建一个函数来获取../../blah/foo对象的实例。
/**
 * Returns a string, or
 * throws an UnexpectedValueException, otherwise.
 */
function isString($string)
{
    if (!is_string($string)) {
        throw new UnexpectedValueException("$string must be a string data type.");
    }

    return $string;
}

/**
 * Returns a mysqli_result object, or throws an `UnexpectedValueException`.
 * You can reuse this for other SELECT, SHOW, DESCRIBE or EXPLAIN queries.
 */
function getMySQLiResult(MySQLi $db, $sql)
{
    $result = $db->query(isString($sql));

    if (!($result instanceof mysqli_result)) {
        throw new UnexpectedValueException("<p>MySQLi error no {$db->errno} : {$db->error}</p>");
    } 

    return $result;
}

2)其次,创建一个函数来存放SQL并调用getmysqliresult()。
/**
 * Make sure you can get the data first.
 * returns a mysqli_result object.
 */
function getInterviews(MySQLi $db)
{
    $sql = "SELECT * FROM `interviews` WHERE `featured` = 1";
    return getMySQLiResult($db, $sql);
}

3)生成一个表数据(mysqli_result)单元格及其内容的函数。把你需要重复的所有html或者数据放在这里。
/**
 * Returns one database table record a table data cell.
 */
function buildCell(array $record)
{
    return "<td>\n".
                '<img src="' .$record['image']. '" alt="' .$record['title']. '">' ."\n".
                '<h4>' .$record['title']. '</h4>' . "\n" .
                '<hr>' . "\n" .
                '<p class="description">' .$record['description']. '</p>' . "\n" .
                '<div id="hovers">
                     <a href="#" class="button">
                         <span class="contentbut">Read More</span>
                     </a>
                 </div>' . "\n 
            </td>\n";
}

4)生成生成表行的函数。小心局部的排。:-)
首先,一个小助手函数。
/**
 * Returns one <tr></tr> element. Helper.
 */
function makeTr($tds)
{
    return "<tr>\n" .isString($tds). "\n</tr>";
}

第二,真正的交易。
function buildTableRow (array $tableRow)
{
    return makeTr(buildCell($tableRow)) . "\n";   //Done!
}

/**
 * Returns a string of multiple <tr></tr> elements,
 * $maxRecords per row.
 */
function buildTableRows(array $tableRows, $numRecords, $maxPerRow)
{
    $rows          = []; // Holds finished groups of <tr>s
    $row           = ''; // Temporary variable for building row of <td>s
    $numCells      = 0;  // Number of cells currently in a row of <td>s.
    $numRows       = (int)($numRecords / $maxPerRow); //Rows to make.
    $numStragglers = $numRecords % $maxPerRow;        // Extra <td>s, partialRow.

    if ($numStragglers !== 0) {  //Check if extra row is needed.
        $numRows += 1;
    }

    foreach ($tableRows as $record)
    {
        $row .= buildCell($record);
        ++$numCells;

        if ($numCells === $numRecords) {  // Builds partial, last row, if needed.
            $rows[] = makeTr($row);
            break;                        // Done!
        }

        if ($numCells === $maxPerRow) {   // Builds full row.
            $rows[]   = makeTr($row);     // Save the row.
            $numCells = 0;                // Start cell counter over.
            $row      = '';               // Start a new row.
        }
    }

    if(count($rows) !== $numRows) {  //Verify all rows were created.
        throw new RuntimeException("Rows (<tr>) for all records were not created!");
    }

    return  implode("\n", $rows) . "\n";  //Return all rows as a string.
}

5)创建一个函数,在页面上弹出所需的HTML。在这种情况下,HTML中只需要一(1)个替换。
/**
 * returns a set of HTML table rows (<tr></tr>) to fill a <tbody>.
 * or, returns an alternative message.
 */
function drawInterviews(MySQLi $db, $maxPerRow) //PDO is recommened. Dependency injection.
{
    $defaultMessage = "<tr>\n<td>There are no featured interviewers.<td>\n<\tr>\n";

    try {
           if (!is_int($maxPerRow) || $maxPerRow < 1) {
              throw new RangeException("The number of interviews per row must be an integer equal to 1, or greater than 1.");
           }

           //Make a robust connection sequence, or pass it in like above.
           //$db       = new mysqli('host', 'user', 'password', 'dbname');
           $result     = getInterviews($db);
           $numRecords = result->num_rows;

           if ($numRecords < 1) {
               return $defaultMessage;
           }

           if ($numRecords === 1) {
               return buildTableRow($result->fetch_assoc()); 
           }                

           return buildTableRows($result->fetch_all(), $numRecords, $maxPerRow);

    } catch (Exception $e)
         //Something went wrong with the query.
         error_log($e->getMessage());
    } finally { //PHP 5.5+
        $result->free();
    }

    return $defaultMessage;
}

6)现在,有一个好的html<td></td>结构。只需要一个插值。假设每行有三条记录…
不管怎样,如果你想要一个表,把这个表“骨架”的副本放在<table>里面,在页眉和页脚之间的某个地方(即html文档的main<td>)。
<table>
    <caption>Featured Interviewers</caption> <!-- Centers above table. -->
    <thead>
        <tr>                  <!-- If needed. -->
            <th>Heading1</th> <!-- If needed. -->
            <th>Heading2</th> <!-- If needed. -->
            <th>Heading3</th> <!-- If needed. -->
        </tr>
    </thead>
    <tfoot></tfoot>           <!-- If needed. Yes, it goes after <thead>. -->
    <tbody>
        <!-- <div id="element1"></div> --> //What goes between here?
        <!-- <div id="content1">       --> //What's this? 
        <?= drawInterviews($db, 3); ?>  <!-- Dependency injection. -->
    </tbody>
</table>    

所有这些都可以变得更加模块化和可重用(甚至面向对象)。
更新:
基于你的Dropbox代码…
学院.php
1)最好的做法是创建一个名为academytest.php的单独php文件,或是其他类似的文件。将除<body>tbodyFiller.php将进入getInterviews()drawInterviews()将进入academyLibray.phpisString()将进入library.php(以前称为getMySQLiResult())之外的所有函数放入此文件。
database.php的开头应该如下所示:
<?php
//                       academytest.php
require '../../includes/library.php';    //For now, put generic helper functions here. Group them, later.
require_once '../../core/database.php';  //Formerly, init.php. Put getMySQLiResult() in here.
require '../../includes/academyLibrary.php'; //Put the two "interview"  functions here.

$db = getMySQLi();  //Many things are dependent on this being here.

require '../../includes/navigation.php';

/***************** DELETE THESE LINES *****************/
//$sql = "SELECT * FROM interviews WHERE featured = 1";
//$featured = $db->query($sql);
/******************************************************/

init.php的页脚中,关闭与数据库的连接。
<!-- ------FOOTER------ -->
<?php
    include '../../includes/footer.php';
    $db->close(); //Ensures $db is available to use in the footer, if necessary.
?>

library.php库
academytest.php的开头应该如下所示:
<?php
//                       library.php

/**
 * Returns a string, or
 * throws an UnexpectedValueException, otherwise.
 */
function isString($string)
{
    if (!is_string($string)) {
        throw new UnexpectedValueException("$string must be a string data type.");
    }

    return $string;
}

我认为academytest.php应该命名为library.php。您可以在空闲时学习使用带有错误检查的面向对象构造函数(使用init.php)序列。最终,你会想学习PDO
另外,制作一个单独的文件来保存您的凭据。现在,这比将它们硬编码到database.php函数要好。
dbcreds.php文件
<?php

//                        dbCreds.php

$host     =  ''; //IP or DNS name: string.
$username =  ''; //Your account: string.
$passwd   =  ''; //The password: string.
$dbname   =  ''; //The database you want to work with: string.

//*************************************************************************
//$port   =  '3306'; //Un-comment and change only if you need a differnt TCP port. 
                     //Also, you would need to add a $port as your last argument in new MySQLi(),
                     //in the getMySQLi() function.

数据库.php
<?php
//                       database.php
/**
 * Returns a mysqli_result object, or throws an `UnexpectedValueException`.
 * You can reuse this for other SELECT, SHOW, DESCRIBE or EXPLAIN queries.
 */
function getMySQLiResult(MySQLi $db, $sql)
{
    $result = $db->query(isString($sql));

    if (!($result instanceof mysqli_result)) {
        throw new UnexpectedValueException("<p>MySQLi error no {$db->errno} : {$db->error}</p>");
    } 

    return $result;
}

function getMySQLi() //This can be improved, but that's not the issue right now.
{
    require_once 'dbCreds.php'; //Choose your own file name. Do not put in public directory.

    $db = new mysqli($host, $username, $passwd, $dbname); //$port would be next.

    if(!($db instanceof MySQLi)){
        throw new UnexpectedValueException("A MySQLi object was not returned during your connection attempt.");
    }

    if(isset($db->connect_error)){
        throw new UnexpectedValueException("The database connection was not established. {$db->connect_errno} : {$db->connect_error}");
    }

    return $db
}  //Using the object form of MySQLi object has side benenfits.

学院图书馆.php
new的开头应该如下所示:
<?php
//                       academyLibrary.php
require 'tbodyFiller.php'; //Put all but four functions in here.

function getInterviews(MySQLi $db)
{
    $sql = "SELECT * FROM `interviews` WHERE `featured` = 1";
    return getMySQLiResult($db, $sql);
}

/**
 * Comments //etc...
 */
function drawInterviews(MySQLi $db, $maxPerRow)
{
    //The code, etc ...
}

如果尚未在getMySQLi()内部配置academyLibrary.php,请确保include_pathphp.ini位于同一目录中。
导航.php
我们将用面向对象的方法替换使用mysql的过程形式。这很简单,我们不需要改变太多。我现在不会替换您的循环或查询,但我的建议是不要把php循环和sql直接放在html中。找到一种使用函数或方法的方法,就像我在academyLibrary.php中为表所做的那样。这时,你应该有足够的例子了。:-)
重构
我花了一些时间重构这个文件。这是我最上面的。再次,您可能希望创建另一个php文件,比如tbodyFiller.php,并将这些函数放入其中。在这种情况下,您可以用一行academytest.php替换下面看到的所有函数。当然,这种导入代码的方式可能取决于在navLibrary.php中配置require 'navLibrary.php';
<?php
//                    navigation.php    

function getPqueryMainData(MySQLi $db)
{
    $sql = "SELECT * FROM `mainmenu` WHERE `parent` = 0";       //pqueryMain
    return getMySQLiResult($db, $sql);
}

function getPqueryData(MySQLi $db)
{
    $sql = "SELECT * FROM `categories` WHERE `parent` = 0";     //pquery
    return getMySQLiResult($db, $sql);
}

function getCquery1Data(MySQLi $db)
{
    $sql = "SELECT * FROM `categories` WHERE `parent` = 1";     //cquery1
    return getMySQLiResult($db, $sql);
}

function getCquery2Data(MySQLi $db, $int)
{
    $sql = "SELECT * FROM `categories` WHERE `parent` = '$int'"; //cquery2
    return getMySQLiResult($db, $sql);
}

//Consider doing at most 3 queries early on.
//Consider using better names for your variables.
//I get that 'p' means "primary", and 'c' means "child", but come on. :-) 

$pqueryMain = getPqueryMainData($db);
$pquery     = getPqueryData($db);
$cquery1    = getCquery1Data($db);
$cquery2    = null;

关于php - PHP:如何使用MySQLi在每个HTML表行中显示多个MySQL表记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42471993/

相关文章:

php - ERR_NAME_NOT_RESOLVED

javascript - 从剪贴板发送文件

javascript - 添加一个类到 input[text]/delete previous append

css - gulp-sass 不导入 scss 文件

php - 当我们从数据库中删除图像时,图像无法从文件夹中删除

php - 使用 PHP 验证来自 login.microsoftonline.com 的 JWT 签名

php - 如何在 Lumen 8.0 中使用 Helper 类?

php - 处理admin系统用户和前端网站用户时如何处理用户权限?

php - 检测 HTML 文本区域中的新行

html - 悬停效果仅适用于特定的 div