【发布时间】:2020-12-16 13:03:47
【问题描述】:
我目前正在开发一个网站,对此我很陌生。我已经使用 connection.php 文件建立了与我的数据库的连接,但似乎很难设置 PHP 文件的样式。 所以我想知道:
- 是否有更智能的方法来使用数据库中的数据进行下拉菜单,如果网站仍然是 .php 文件,我将如何包含和设置网站样式?
- 我的偏好是使用 HTML 和 CSS 创建一个好看的网站。但我不知道如何将我的下拉菜单包含在数据库中的数据中?
因为现在所有内容都在一个文件中,所以看起来像这样
提前谢谢你
Index.php
<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);
$host='database.****.us-east-1.rds.amazonaws.com';
$db = '****';
$port = 5432;
$username = 'postgres';
$password = '****';
try {
$conn = new PDO("pgsql:host=$host;port=$port;dbname=$db;user=$username;password=$password");
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<body>
<h1>Choose Category</h1>
<?php
$sql ="select * from products inner join category on category.category_id = products.category";
//Prepare the select statement.
$stmt = $conn->prepare($sql);
//Execute the statement.
$stmt->execute();
//Retrieve the rows using fetchAll.
$users = $stmt->fetchAll();
// show menu from dropdown
?>
<select>
<?php foreach($users as $user): ?>
<option value="<?= $user['id']; ?>"><?= $user['name']; ?></option>
<?php endforeach; ?>
</select>
</body>
</html>
【问题讨论】:
-
如果您想要一种“更智能”的方式,您可以阅读 MVC 模式(用于 PHP)。或者更聪明的是,使用现有的框架。在样式方面,与普通的 HTML 页面没有区别,因为 PHP 代码是在服务器上执行的,并且只将输出返回给客户端,在上面的代码中只是 HTML。
-
绝对建议将您的代码分离为 MVC(模型、视图、控制器)模式或使用已创建的框架。使其更清洁(这意味着更易于维护)并为您完成大量繁重的工作。
-
谢谢大家,我会看看!
标签: php html postgresql