当然可以!以下是一些PHP编程练习,可以帮助你提高你的PHP技能,这些练习涵盖了从基础到高级的各个方面。
1. Hello World
<?php echo "Hello, World!"; ?>
2. 计算两数之和
<?php function add($a, $b) { return $a + $b; } $num1 = 5; $num2 = 3; echo "Sum: " . add($num1, $num2); ?>
3. 表单处理
创建一个HTML表单,并在提交时使用PHP处理数据:
HTML (index.html)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form Submission</title> </head> <body> <form action="process.php" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name"><br><br> <input type="submit" value="Submit"> </form> </body> </html>
PHP (process.php)
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST['name']; echo "Hello, " . htmlspecialchars($name) . "!"; } else { echo "Invalid request method."; } ?>
4. 用户登录系统
HTML (login.html)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User Login</title> </head> <body> <form action="login.php" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username"><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password"><br><br> <input type="submit" value="Login"> </form> </body> </html>
PHP (login.php)
<?php session_start(); $users = [ 'user1' => 'password1', 'user2' => 'password2' ]; if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_POST['username']; $password = $_POST['password']; if (isset($users[$username]) && $users[$username] === $password) { $_SESSION['username'] = $username; echo "Login successful!"; } else { echo "Invalid credentials!"; } } else { echo "Invalid request method."; } ?>
5. 数据库连接与查询
假设你已经安装并配置好了MySQL数据库,并且有一个名为testdb
的数据库和一个名为users
的表。
数据库结构(SQL)
CREATE DATABASE testdb; USE testdb; CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) NOT NULL, password VARCHAR(50) NOT NULL );
PHP (connect.php)
<?php $servername = "localhost"; $username = "root"; // 修改为你的数据库用户名 $password = ""; // 修改为你的数据库密码 $dbname = "testdb"; // 修改为你的数据库名 // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>
PHP (query.php)
<?php include 'connect.php'; $sql = "SELECT * FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出每行数据 while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " Name: " . $row["username"]. " Password: " . $row["password"]. "<br>"; } } else { echo "0 results"; } $conn->close(); ?>
小伙伴们,上文介绍php编程练习_PHP的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/85142.html