【问题标题】:What is the best way to include php database data with HTML用 HTML 包含 php 数据库数据的最佳方法是什么
【发布时间】:2020-12-16 13:03:47
【问题描述】:

我目前正在开发一个网站,对此我很陌生。我已经使用 connection.php 文件建立了与我的数据库的连接,但似乎很难设置 PHP 文件的样式。 所以我想知道:

  1. 是否有更智能的方法来使用数据库中的数据进行下拉菜单,如果网站仍然是 .php 文件,我将如何包含和设置网站样式?
  2. 我的偏好是使用 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


【解决方案1】:

有一个更简单的方法,但我将举一个例子: 假设你有一个 php 文件:

connection.php:

<?php
function connect(){
$con=mysqli_connect("localhost","root","","dbname");
if(!$con)
die("Could not connect");
}

return $con;
}
?>

现在是另一个名为 getAll.php 的文件

<?php
require("connection.php");
$con=connect();
$getAll="select * from employees";
$res=mysqli_query($con,$getAll);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[firstname]'>$row['firstname']</option>"
}
mysqli_close($con);

?>

现在你想在哪里显示下拉列表:

假设有一个名为 display.php 的文件

<html>
     <body>
          <select name="employee">
          <?php
          require("getAll.php");
          ?>
          </select>
     </body>
</html>

这是一种从数据库中获取数据并显示它们的简单方法。

【讨论】:

  • 是否有可能有一个 HTML 文件,我的 css 在哪里。然后选择一个下拉列表,其中包含来自数据库的数据的 php。还是我必须做 php 网站。
  • 要从数据库中获取数据,您必须创建一个 php 文件而不是 html 文件。你仍然可以在其中包含 css。
  • 您总是可以将 php 文件视为 html 文件。
猜你喜欢
  • 2010-09-14
  • 2010-09-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多