PHP常用代码样例
以下是一些常用的PHP代码样例,涵盖了基本的语法和功能。
(图片来源网络,侵删)
1. 输出文本
<?php echo "Hello, World!"; ?>
2. 变量声明和使用
<?php $name = "Alice"; echo "Hello, $name!"; ?>
3. 条件语句
<?php $age = 25; if ($age >= 18) { echo "You are an adult."; } else { echo "You are a minor."; } ?>
4. 循环语句
4.1 for循环
(图片来源网络,侵删)
<?php for ($i = 0; $i < 5; $i++) { echo $i . "<br>"; } ?>
4.2 while循环
<?php $count = 0; while ($count < 5) { echo $count . "<br>"; $count++; } ?>
5. 数组操作
<?php $fruits = array("apple", "banana", "cherry"); echo $fruits[0]; // 输出 "apple" ?>
6. 函数定义与调用
<?php function greet($name) { echo "Hello, $name!"; } greet("Bob"); // 输出 "Hello, Bob!" ?>
7. 表单处理
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST["name"]; echo "Hello, $name!"; } ?> <form method="post"> Name: <input type="text" name="name"><br> <input type="submit"> </form>
8. 数据库连接与查询
(图片来源网络,侵删)
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // 执行SQL查询 $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出数据 while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 results"; } $conn->close(); ?>
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/46052.html