- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想在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
设置,则可以将其设置为一个目录或任何适当目录组。这样,您就可以按您所需的方式在目录中排列文件,并且您的include
、include_once
、require
和require_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.
include_path
以便您不必一直这样做。
../../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;
}
/**
* 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);
}
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";
}
/**
* 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.
}
/**
* 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;
}
<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>
academytest.php
的单独php文件,或是其他类似的文件。将除
<body>
和
tbodyFiller.php
将进入
getInterviews()
、
drawInterviews()
将进入
academyLibray.php
和
isString()
将进入
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.
?>
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
函数要好。
<?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
// 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.
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_path
和
php.ini
位于同一目录中。
academyLibrary.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/
我在 JavaScript 文件中运行 PHP,例如...... var = '';). 我需要使用 JavaScript 来扫描字符串中的 PHP 定界符(打开和关闭 PHP 的 )。 我已经知道使
我希望能够做这样的事情: php --determine-oldest-supported-php-version test.php 并得到这个输出: 7.2 也就是说,php 二进制检查 test.
我正在开发一个目前不使用任何框架的大型 php 站点。我的大问题是,随着时间的推移慢慢尝试将框架融入应用程序是否可取,例如在创建的新部件和更新的旧部件中? 比如所有的页面都是直接通过url服务的,有几
下面是我的源代码,我想在同一页面顶部的另一个 php 脚本中使用位于底部 php 脚本的变量 $r1。我需要一个简单的解决方案来解决这个问题。我想在代码中存在的更新查询中使用该变量。 $name)
我正在制作一个网站,根据不同的情况进行大量 PHP 重定向。就像这样...... header("Location: somesite.com/redirectedpage.php"); 为了安全起见
我有一个旧网站,我的 php 标签从 因为短标签已经显示出安全问题,并且在未来的版本中将不被支持。 关于php - 如何避免在 php 文件中写入
我有一个用 PHP 编写的配置文件,如下所示, 所以我想用PHP开发一个接口(interface),它可以编辑文件值,如$WEBPATH , $ACCOUNTPATH和 const值(value)观
我试图制作一个登录页面来学习基本的PHP,首先我希望我的独立PHP文件存储HTML文件的输入(带有表单),但是当我按下按钮时(触发POST到PHP脚本) )我一直收到令人不愉快的错误。 我已经搜索了S
我正在寻找一种让 PHP 以一种形式打印任意数组的方法,我可以将该数组作为赋值包含在我的(测试)代码中。 print_r 产生例如: Array ( [0] => qsr-part:1285 [1]
这个问题已经有答案了: 已关闭11 年前。 Possible Duplicate: What is the max key size for an array in PHP? 正如标题所说,我想知道
我正在寻找一种让 PHP 以一种形式打印任意数组的方法,我可以将该数组作为赋值包含在我的(测试)代码中。 print_r 产生例如: Array ( [0] => qsr-part:1285 [1]
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 9 年前。 Improve this ques
我在 MySQL 数据库中有一个表,其中存储餐厅在每个工作日和时段提供的菜单。 表结构如下: i_type i_name i_cost i_day i_start i_
我有两页。 test1.php 和 test2.php。 我想做的就是在 test1.php 上点击提交,并将 test2.php 显示在 div 中。这实际上工作正常,但我需要向 test2.php
我得到了这个代码。我想通过textarea更新mysql。我在textarea中回显我的MySQL,但我不知道如何更新它,我应该把所有东西都放进去吗,因为_GET模式没有给我任何东西,我也尝试_GET
首先,我是 php 的新手,所以我仍在努力学习。我在 Wordpress 上创建了一个表单,我想将值插入一个表(data_test 表,我已经管理了),然后从 data_test 表中获取所有列(id
我有以下函数可以清理用户或网址的输入: function SanitizeString($var) { $var=stripslashes($var); $va
我有一个 html 页面,它使用 php 文件查询数据库,然后让用户登录,否则拒绝访问。我遇到的问题是它只是重定向到 php 文件的 url,并且从不对发生的事情提供反馈。这是我第一次使用 html、
我有一个页面充满了指向 pdf 的链接,我想跟踪哪些链接被单击。我以为我可以做如下的事情,但遇到了问题: query($sql); if($result){
我正在使用 从外部文本文件加载 HTML/PHP 代码 $f = fopen($filename, "r"); while ($line = fgets($f, 4096)) { print $l
我是一名优秀的程序员,十分优秀!