以下是一些常见的PHP范例代码,涵盖了基本的语法、数组操作、字符串处理、文件操作和数据库连接等方面:
基本语法 php复制<?php // 声明变量 $name = "John"; $age = 30; // 输出变量 echo "Name: " . $name . ", Age: " . $age; // 条件语句 if ($age > 18) { echo "You are an ***."; } else { echo "You are a minor."; } // 循环语句 for ($i = 0; $i < 5; $i++) { echo "Hello, World!"; } ?> 数组操作 php复制<?php // 声明数组 $fruits = array("apple", "banana", "cherry"); // 访问数组元素 echo $fruits; // 输出: apple // 遍历数组 foreach ($fruits as $fruit) { echo $fruit . ""; } // 添加数组元素 $fruits[] = "orange"; // 删除数组元素 unset($fruits); // 获取数组长度 $count = count($fruits); ?> 字符串处理 php复制<?php // 声明字符串 $str = "Hello, World!"; // 字符串长度 $length = strlen($str); // 查找子字符串 $pos = strpos($str, "World"); // 替换子字符串 $newStr = str_replace("World", "PHP", $str); // 转换为大写 $upperStr = strtoupper($str); // 转换为小写 $lowerStr = strtolower($str); ?> 文件操作 php复制<?php // 打开文件 $file = fopen("example.txt", "r"); // 读取文件内容 $content = fread($file, filesize("example.txt")); // 写入文件内容 fwrite($file, "Hello, World!"); // 关闭文件 fclose($file); ?> 数据库连接 php复制<?php // 数据库连接参数 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // SQL查询 $sql = "SELECT * FROM table_name"; $result = $conn->query($sql); // 处理结果集 if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "id: " . $row["id"] . ", name: " . $row["name"]; } } else { echo "0 results"; } // 关闭连接 $conn->close(); ?>这些范例代码提供了一个基础,可以帮助你理解和掌握PHP编程的基本概念和常用操作。你可以根据自己的需求进行扩展和修改。
详细说说本文来源于网络不代表本站立场!版权归原作者所有,如果转发请带上原文链接注明出处!文章内容仅供参考,不能盲信。
爱范例网https://www.fanli2.com
本文链接: https://www.fanli2.com/fanli/45735.html