How to Generate Dynamic Web Pages with PHP: A Step‑by‑Step Guide
This tutorial walks through setting up a PHP development environment, creating .php files, embedding PHP within HTML, and using PHP to output the current time, handle form submissions, and interact with a MySQL database to build dynamic web pages.
PHP is a widely used scripting language for web development that can be combined with HTML to generate dynamic pages, offering richer and personalized user experiences.
Step 1: Set up the PHP development environment – install a web server (Apache) and the PHP interpreter, typically using bundles such as WAMP, MAMP, or XAMPP that also include MySQL.
Step 2: Create a .php file – open a text editor and save a file with the .php extension, for example index.php , which will contain the PHP code.
Step 3: Embed PHP in HTML – place PHP code between <?php … ?> tags inside an HTML document. A simple example is:
<!DOCTYPE html>
<html>
<body>
<h1>欢迎来到我的网站!</h1>
<?php
echo "当前时间是:" . date("Y-m-d H:i:s");
?>
</body>
</html>The script outputs the current date and time when the page is loaded.
Step 4: Generate dynamic content from user input – retrieve form data with $_POST and use it to produce personalized output. Example:
<!DOCTYPE html>
<html>
<body>
<h1>欢迎来到我的网站!</h1>
<?php
// 获取用户提交的表单数据
$name = $_POST['name'];
$age = $_POST['age'];
// 根据用户的输入生成动态内容
echo "你好," . $name . "!你今年" . $age . "岁了。";
?>
<form method="post" action="">
姓名:<input type="text" name="name"><br>
年龄:<input type="text" name="age"><br>
<input type="submit" value="提交">
</form>
</body>
</html>This code captures the user's name and age and displays a customized greeting.
Step 5: Interact with a MySQL database – use the mysqli extension to connect, query, and display results. Example:
<?php
// 连接数据库
$conn = mysqli_connect("localhost", "username", "password", "database");
// 检查数据库连接是否成功
if (! $conn) {
die("数据库连接失败:" . mysqli_connect_error());
}
// 从数据库中查询数据
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
// 输出查询结果
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "用户名:" . $row["username"] . "
";
}
} else {
echo "没有查询到数据。";
}
// 关闭数据库连接
mysqli_close($conn);
?>The script connects to MySQL, runs a SELECT query, and prints each username or a message if no data is found.
By following these steps you can start building dynamic web pages with PHP, and further explore its many additional features.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.