PHP 代码大全涉及到的范围非常广泛,因为 PHP 是一门功能丰富的编程语言,主要用于 Web 开发。
这里,我们将简要介绍一些常用的 PHP 代码及其含义。
为了便于理解,我们将其分为几个类别:
基本语法
:PHP 代码块的开始和结束标签。
//
或 #
,多行注释使用 /* ... */
。// 这是一个单行注释
# 这也是一个单行注释
/*
这是一个
多行注释
*/
$
符号声明变量。$name = "John";
$age = 30;
echo
或 print
输出文本或变量。echo "Hello, World!";
print $name;
控制结构
if
、else
和 elseif
):if ($age = 18 && $age < 65) {
echo "You are an adult.";
} else {
echo "You are a senior.";
}
for
、while
和 foreach
):// for 循环
for ($i = 0; $i < 5; $i++) {
echo $i;
}
// while 循环
$count = 0;
while ($count < 5) {
echo $count;
$count++;
}
// foreach 循环
$names = array("Alice", "Bob", "Charlie");
foreach ($names as $name) {
echo $name;
}
函数
function greet($name) {
echo "Hello, " . $name . "!";
}
greet("John");
// 字符串长度
echo strlen("Hello, World!");
// 查找子字符串
echo strpos("Hello, World!", "World");
// 时间
echo date("Y-m-d");
数组
$array1 = array("Apple", "Banana", "Cherry");
$array2 = ["Apple", "Banana", "Cherry"];
$person = array("name" => "John", "age" => 30);
文件和 I/O
$content = file_get_contents("example.txt");
echo $content;
$content = "Hello, World!";
file_put_contents("example.txt", $content);
这里只是对 PHP 常用代码的简要介绍。PHP 有大量的内置函数、特性和扩展,可以在官方文档中找到详细的信息:https://www.php.net/manual/en/index.php。
在实际开发中,你可能还需要处理更复杂的任务,例如操作数据库、处理表单数据、处理文件上传、使用会话等。
以下是一些这些任务的简要示例:
数据库操作(以 MySQLi 为例)
$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 = "SELECT id, name FROM users";
$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";
}
$sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . $conn->error;
}
$conn->close();
处理表单数据
Name:
Email:
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: " . $name . " - Email: " . $email;
文件上传
Select file to upload:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}