本文介绍了PHP:如何使用MySQLi为每个HTML表格行显示多个MySQL表记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想在mysql数据库的php中显示一组元素。我已经做到了,但我的数据出现在一个长栏中。我希望每一个新的元素都能一个接一个出现。 下面是我所得到的截图。我想第一个旁边的第二个: https://www.dropbox.com/s/2y3g0n7hqrjp8oz/Capture.PNG?dl=0 以下是我的代码: <?php require_once'core / init.php'; 包含'includes / navigation.php'; $ sql =SELECT * FROM interviews WHERE featured = 1; $ featured = $ db-> query($ sql); < html> 在此输入代码 在此处输入代码 < link href =http:// localhost /menu/css/academy.cssrel =stylesheet`在此处输入代码`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为H. < div id =hovers> < a href =#class =button> < span class =contentbut>阅读更多< / span> < / a> < / div> < / th> < / tr> < / table> < / div> < / div> 请帮忙。 p> 谢谢!解决方案 简介 注:此答案详细信息将创建一个多记录到一行排列。然而,这个答案可以改变,以提供一个单一记录到一行安排。 分离问题 em>将帮助您编写更简洁的代码。分离关注点将使维护代码变得更容易。清洁代码松散耦合,不受嵌入式依赖关系的负担。 Clean代码在函数签名和类构造函数中标识它的依赖关系,预期这些需求将在外部实现。干净的代码具有紧密的凝聚力。这意味着函数/方法只有一个任务,而类只有一个目标。干净的代码通常反映在一个已经细化和完善的任务中(但并非总是)。干净的代码是我追求的理想,但没有人是完美的。 尝试设法获得尽可能多的 SQL HTML 文件中的和 PHP 。内插变量并显示函数的返回结果只能使HTML更易于阅读。 也是很好的HTML结构。 分解动态构建< table> 基于SQL查询的结果是非常可能的。最终,您可能会决定使用 CSS 和 divs 来设计样式和响应。这个代码可以被改变来实现这一点(毕竟,你只是将行堆叠)。 $ b 最后,创建一个OOP类(使用自定义命名空间)对于模块化代码以及将绝大多数符号(变量名等)从全局命名空间中取出非常有用。 在我们开始之前:php.ini:include_path 你想设置一个逻辑目录结构 在 php.ini中设置 include_path / code>。 如果您搜索 php.ini c $ c> include_path 设置,您可以将其设置为一个目录或任何一组适当的目录。这样,你就可以按照你想要的方式安排你的文件,并且你的包含, include_once , require 和 require_once 语句仍然会找到他们想要导入的文件。您不必像 /dir/dir/file.php 或相对路径(如 ../../ core / database)键入绝对路径。 PHP 。在这两种情况下,您都可以指定文件名。 示例: include'file.php'; //查找文件是否位于include_path中。 需要'database.php'; //查找文件是否位于include_path中。注意:保存库文件和其他纯PHP编码文件(等等)。保存库文件和其他纯粹的PHP编码文件(例如:http://www.ibm.com/developerworks/cn/data/index.html)。 ..)退出webroot或任何可公开访问的目录。将它们逻辑地保持在Webroot上方。设置 include_path ,所以你不必一直在做 ../../ blah / foo 。 任务 1 )首先,创建一个获取 mysqli_result 对象实例的函数。 / ** *返回一个字符串,否则 *抛出一个UnexpectedValueException异常。 * / 函数isString($ string) { if(!is_string($ string)){ throw new UnexpectedValueException($ string must be a string数据类型。); } return $ string; } / ** *返回一个mysqli_result对象,或者抛出一个`UnexpectedValueException`。 *您可以将其用于其他SELECT,SHOW,DESCRIBE或EXPLAIN查询。 * / 函数getMySQLiResult(MySQLi $ db,$ sql) { $ result = $ db-> query(isString($ sql)); if(!($ result instanceof mysqli_result)){ throw new UnexpectedValueException(< p> MySQLi错误否{$ db-> errno}:{$ db->错误}< / p>中); } 返回$ result; } 2 )其次,你的SQL并调用getMySQLiResult()。 / ** *确保您可以先获取数据。 *返回一个mysqli_result对象。 * / 函数getInterviews(MySQLi $ db) { $ sql =SELECT * FROM`interviews` where'featured` = 1; 返回getMySQLiResult($ db,$ sql); } 3 )建立一个表格数据(< td>< / td> )单元格及其内容。将 all 所需的HTML或数据放入 为每个记录重复 。 / ** *返回一个数据库表记录一个表数据单元。 * / 函数buildCell(array $ record) { return< td> \\\。 '< img src =''。$ record ['image']。'alt ='。$ record ['title']。'>'。\\\。 '< h4>'。$ record ['title']。 '< / h4>'。 \\\。 '< hr>'。 \\\。 '< p class =description>'。$ record ['description']。 '< / p>'。 \\\。 '< div id =hovers> < a href =#class =button> < span class =contentbut>了解详情< / span> < / a> < / div>'。 \\\ < / td> \\\; } 4 )建立表格行。警惕部分行。 : - ) 第一个,一个小帮手函数。 / ** *返回一个< tr>< / tr>元件。帮手。 * / 函数makeTr($ tds) { return< tr> \\\.isString($ tds)。 \\\< / TR> 中; } 第二个,真正的交易。 函数buildTableRow(array $ tableRow) { return makeTr(buildCell($ tableRow))。 \\\; //完成! } / ** *返回多个< tr>< / tr>元素,每行 * $ maxRecords。 * / 函数buildTableRows(array $ tableRows,$ numRecords,$ maxPerRow) { $ rows = []; //持有< tr> s $ row =''; //构建< td>行的临时变量s $ numCells = 0; //当前在< td>行中的单元格的数量。 $ numRows =(int)($ numRecords / $ maxPerRow); //行使。 $ numStragglers = $ numRecords%$ maxPerRow; // Extra< td> s,partialRow。 if($ numStragglers!== 0){//检查是否需要额外的行。 $ numRows + = 1; foreach($ tableRows as $ record) { $ row。= buildCell($ record); ++ $ numCells; if($ numCells === $ numRecords){//根据需要构建部分最后一行。 $ rows [] = makeTr($ row); 休息; //完成! } if($ numCells === $ maxPerRow){//构建完整行。 $ rows [] = makeTr($ row); //保存该行。 $ numCells = 0; //启动细胞计数器结束。 $ row =''; //开始一个新行。 if(count($ rows)!== $ numRows){//验证所有行已创建。 抛出新的RuntimeException(没有创建所有记录的行(< tr>)!); } 返回implode(\\\,$ rows)。 \\\; //将所有行作为字符串返回。 } 5 )创建一个函数,你需要在你的页面上使用HTML。在这种情况下,您只需要一次(1)替换即可出现在HTML中。 / ** *返回一组HTML表格行(< tr>< / tr>)以填充< tbody> ;. *或者,返回一个替代消息。 * / 函数drawInterviews(MySQLi $ db,$ maxPerRow)//推荐PDO。依赖注入。 { $ defaultMessage =< tr> \\\< td>没有有特色的访问者< td> \\\< \ tr> \\\; 尝试{ if(!is_int($ maxPerRow)|| $ maxPerRow< 1){ throw new RangeException(每行的访问次数必须是整数等于1,或大于1。 } //建立一个健壮的连接序列,或者像上面那样传递它。 // $ 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()); } 返回buildTableRows($ result-> fetch_all(),$ numRecords,$ maxPerRow); } catch(Exception $ e) //查询出错了。 error_log($ e-> getMessage()); } finally {// PHP 5.5+ $ result-> free(); } return $ defaultMessage; } 6 )现在, code>< table> 结构。只需要一个插值。假设每行有三个< td> s(记录)... 无论如何,如果你想要一个表,在 academytest.php 内放置此表skeleton的副本,位于标题和)。 <表> < caption>精选Interviewers< / caption> <! - 上表中心。 - > < thead> < tr> <! - 如果需要的话。 - > < th>标题1< / th> <! - 如果需要的话。 - > < th> Heading2< / th> <! - 如果需要的话。 - > < th> Heading3< / th> <! - 如果需要的话。 - > < / tr> < / thead> < tfoot>< / tfoot> <! - 如果需要的话。是的,它在< thead>之后。 - > < tbody> <! - < div id =element1>< / div> - > //这里有什么? <! - < div id =content1> - > //这是什么? <?= drawInterviews($ db,3); ?> <! - 依赖注入。 - > < / tbody> < / table> 所有这些都可以更加模块化和可重用(面向对象,甚至)。 更新: 基于您的Dropbox代码... p> academytest.php 1 )最好的办法是创建一个单独的PHP名为 tbodyFiller.php 的文件,或者这个文件。将所有函数放在这个文件中, 除了 getInterviews()和 drawInterviews()外 这将进入 academyLibray.php , isString(),它将进入 library.php 和 getMySQLiResult()它将进入 database.php (以前 init.php )。 $ b $ $ c> academytest.php 应该如下所示: <?php // academytest.php 需要'../../includes/library.php'; //现在,在这里放置通用的辅助函数。稍后将它们分组。 require_once'../../core/database.php'; //以前,init.php。把getMySQLiResult()放在这里。 需要'../../includes/academyLibrary.php'; //将两个采访功能放在这里。 $ db = getMySQLi(); //很多事情都依赖于这里。 需要'../../includes/navigation.php'; / *****************删除这些行***************** / // $ sql =SELECT * FROM interviews WHERE featured = 1; // $ featured = $ db-> query($ sql); / ********************************************* ********* / 在的脚注中academytest .php ,关闭与数据库的连接。 <! - ---- --FOOTER ------ - > <?php 包括'../../includes/footer.php'; $ db-> close(); //如果需要,确保$ db可用于页脚。 ?> library.php library.php 的开头应该如下所示: <?php // library.php / ** *返回一个字符串或 *抛出一个UnexpectedValueException,否则。 * / 函数isString($ string) { if(!is_string($ string)){ throw new UnexpectedValueException($ string must be a string数据类型。); } return $ string; } 我认为 init.php 应该被命名为 database.php 。您可以学习如何在闲暇时使用面向对象的构造函数(使用 new )序列进行错误检查。最终,您需要学习 PDO 。 另外,制作一个单独的文件来保存您的凭证。现在,这比将它们编码到 getMySQLi()函数更好。 dbCreds.php <?php // dbCreds.php $主机=''; // IP或DNS名称:字符串。 $ username =''; //您的帐户:字符串。 $ passwd =''; //密码:字符串。 $ dbname =''; //你想要使用的数据库:string。 // **************************************** ********************************* // $ port ='3306'; //仅当您需要不同的TCP端口时才能取消注释和更改。 //此外,您需要在getMySQLi()函数中的新MySQLi(), //中添加$ port作为最后一个参数。 database.php <?php // database.php / ** *返回一个mysqli_result对象,或者抛出一个`UnexpectedValueException`。 *您可以将其用于其他SELECT,SHOW,DESCRIBE或EXPLAIN查询。 * / 函数getMySQLiResult(MySQLi $ db,$ sql) { $ result = $ db-> query(isString($ sql)); if(!($ result instanceof mysqli_result)){ throw new UnexpectedValueException(< p> MySQLi错误否{$ db-> errno}:{$ db->错误}< / p>中); } 返回$ result; } 函数getMySQLi()//这可以改进,但这不是现在的问题。 { require_once'dbCreds.php'; //选择你自己的文件名。不要放在公共目录中。 $ db = new mysqli($ host,$ username,$ passwd,$ dbname); // $ port将是下一个。 if(!($ db instanceof MySQLi)){ throw new UnexpectedValueException(在连接尝试期间没有返回MySQLi对象。 if(isset($ db-> connect_error)){ throw new UnexpectedValueException(数据库连接未建立。{$ db-> connect_errno} :{$ db-> connect_error}); } 返回$ db } //使用MySQLi对象的对象形式有侧边限制。 academyLibrary.php academyLibrary.php 的开头应该如下所示: <?php // academyLibrary.php 需要'tbodyFiller.php'; //将除了四个函数都放在这里。 函数getInterviews(MySQLi $ db) { $ sql =SELECT * FROM`interviews` WHERE`featured` = 1; 返回getMySQLiResult($ db,$ sql); $ b / ** *注释//等等... * / 函数drawInterviews(MySQLi $ db,$ maxPerRow) { //代码等等​​... } 如果您尚未在 php.ini 内配置 include_path ,请确保 academyLibrary。 php 和 tbodyFiller.php 位于 same 目录中。 navigation.php 我们将取代程序化的工作形式与面向对象的MySQL一起使用。这很简单,我们不需要改变太多。我现在不会替换你的循环或查询,但是我的建议是避免将HTML循环和SQL 直接放入HTML中的习惯。找到一种方法来使用函数或方法,就像我在 academytest.php 中为表格所做的那样。到这个时候,你应该有足够的例子。 : - ) 重构 我花了一些时间来重构这个文件。这是我的顶部。 再次,您可能希望创建另一个PHP文件,比如 navLibrary.php ,并将这些函数放入其中。在这种情况下,你可以用下面的代码替换下面所有的函数, require'navLibrary.php'; 。自然,这种导入代码的方式可能取决于在 php.ini 中配置 include_path 。 <?php // navigation.php 函数getPqueryMainData(MySQLi $ db) { $ sql =SELECT * FROM`mainmenu` WHERE`parent` = 0; // pqueryMain return getMySQLiResult($ db,$ sql); 函数getPqueryData(MySQLi $ db) { $ sql =SELECT * FROM`categories` WHERE`parent` = 0; // pquery return getMySQLiResult($ db,$ sql); 函数getCquery1Data(MySQLi $ db) { $ sql =SELECT * FROM`categories` WHERE`parent` = 1; // cquery1 return getMySQLiResult($ db,$ sql); $ b $ function getCquery2Data(MySQLi $ db,$ int) { $ sql =SELECT * FROM`categories` WHERE`parent` ='$ int ; // cquery2 return getMySQLiResult($ db,$ sql); } //考虑在早期最多做3次查询。 //考虑为变量使用更好的名称。 //我得到'p'表示主要,而'c'表示孩子,但是来吧。 :-) $ pqueryMain = getPqueryMainData($ db); $ pquery = getPqueryData($ db); $ cquery1 = getCquery1Data($ db); $ cquery2 = null; I would like to display a group of elements in a row in php from mysql database. I already did it, but my data appears in one long column. I would like every new element to appear one next to the other. Here is a screenshot of what I get. I would like to the first one to be next to the second one: https://www.dropbox.com/s/2y3g0n7hqrjp8oz/Capture.PNG?dl=0Here is my code: <?php require_once 'core/init.php'; include 'includes/navigation.php'; $sql = "SELECT * FROM interviews WHERE featured = 1"; $featured = $db->query($sql); <html>enter code hereenter 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>Please, help.Thank you! 解决方案 IntroductionNote: This answer details creating a many-records-to-one-row arrangement. However, this answer can be altered to provide a single-record-to-one-row arrangement.Separating concerns will help you write cleaner code. Separating concerns will make it easier to maintain your code. Clean code is loosely coupled, unburdened by embedded dependencies. Clean code identifies its dependencies in function signatures and class constructors with the expectation that these needs will be fulfilled externally. Clean code has tight cohesion. This means functions/methods have a single task, and classes have a single objective. Clean code is often reflected in a task that has been broken down and refined (but, not always). Clean code is an ideal I strive for, but no one is perfect.Try to think of ways to get as much SQL and PHP out of your HTML files. Interpolating variables and showing the return results of functions only can make your HTML much easier to read. Good HTML structure counts, too.Breaking down the task of dynamically building a <table> based on the results of a SQL query is very possible. Eventually, you may decide to use CSS and divs for styling and responsiveness reasons. This code can be altered to achieve this (after all, you'd just be stacking boxes in rows).Eventually, creating an OOP class (with custom namespaces) would be great for modularizing your code and getting the vast majority of your symbols (variable names, etc) out of the global namespace.Before we get going: php.ini: include_pathDo you want to setup a logical directory architecture for your project?Set the include_path inside of php.ini.If you search your php.ini for the include_path setting, you can set this to one directory, or any group of appropriate directories. This way, you can arrange your files in directories the way you desire, and your include, include_once, require, and require_once statements will still find the files they want to import. You will not have to type absolute paths like/dir/dir/file.php or relative paths like ../../core/database.php. In both cases, you could just specify the filename.Example: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.Note: Keep library files and other pure PHP coding files (etc ...) out of the webroot, or any publicly accessible directories. Keep them logically above the webroot. Set the include_path so you do not have to keep doing ../../blah/foo all of the time.Tasks1) First, make a function for getting an instance of a mysqli_result object./** * 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) Second, make a function to house your SQL and invoke 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) Make a function for building a table data (<td></td>) cell and its content. Put all HTML or data that you need to repeat for each record in here./** * 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) Make a function for building table rows. Be wary of partial rows. :-)First, a little helper function./** * Returns one <tr></tr> element. Helper. */function makeTr($tds){ return "<tr>\n" .isString($tds). "\n</tr>";}Second, the real deal.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) Make a function that spits out the HTML you need on your page. In this case, you only need one (1) substitution to appear in the HTML./** * 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) Now, have a good HTML <table> structure. Only one interpolation needed. Assuming three <td>s (records) per row ...Anyway, if you want a table, put a copy of this table "skeleton" inside of academytest.php, somewhere between the header and the footer (i.e. the main <body> of the HTML document).<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> All of this can be made more modular and reusable (object-oriented, even).Update:Based on your Dropbox code ...academytest.php1) The best thing to do is create a separate PHP file named tbodyFiller.php, or something to that effect. Put all the functions in this file, except for getInterviews() and drawInterviews() which will go into academyLibray.php, isString() which will go into library.php, and getMySQLiResult() which will go in database.php (formerly init.php).The beginning of academytest.php should look like this:<?php// academytest.phprequire '../../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);/******************************************************/In the footer of academytest.php, close the connection to your database.<!-- ------FOOTER------ --><?php include '../../includes/footer.php'; $db->close(); //Ensures $db is available to use in the footer, if necessary.?>library.phpThe beginning of library.php should look like this:<?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;}I think init.php should be named database.php. You can learn to use the object oriented constructor (using new) sequence with error checking at your leisure. Eventually, you will want to learn PDO.Also, make a separate file to hold your credentials. Right now, this is better than hard coding them in to the getMySQLi() function.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.database.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.academyLibrary.phpThe beginning of academyLibrary.php should look like this:<?php// academyLibrary.phprequire '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 ...}If you have not configured your include_path inside of the php.ini, make sure academyLibrary.php and tbodyFiller.php are located in the same directory.navigation.phpWe are going to replace the procedural forms of working with MySQL with the object-oriented ones. This is simple, and we do not need to change much. I will not replace your loops or queries at this time, but my advice is to get out of the habbit of putting PHP loops and SQL directly in your HTML. Find a way to use a function or method, like I did for the table's in academytest.php. By this time, you should have enough examples. :-)RefactoringI took some time to refactor this file. Here is what I have at the top. Once again, you may wish to create another PHP file, say navLibrary.php, and put these functions into it. In that case you would replace all the functions seen below with one line, require 'navLibrary.php';. Naturally, this way of importing code may depend on configuring your include_path inside of the php.ini.<?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:如何使用MySQLi为每个HTML表格行显示多个MySQL表记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-24 22:03