深入了解PHP:從入門到精通
引言:
PHP是一種廣泛應用於web開發的伺服器端腳本語言,它簡單易學,適用於初學者,也提供了豐富的功能和擴充性,能夠滿足複雜的開發需求。本文將從入門到精通,透過具體的程式碼範例,帶您逐步了解PHP的各個面向。
一、基礎知識
變數宣告與輸出
$name = "John"; $age = 25; echo "My name is " . $name . " and I am " . $age . " years old.";
條件語句
$score = 90; if ($score >= 60) { echo "You passed the exam!"; } else { echo "You failed the exam."; }
循環語句
for ($i = 0; $i < 5; $i++) { echo $i; }
函數的定義和呼叫
function sayHello($name) { echo "Hello, " . $name . "!"; } sayHello("Tom");
二、陣列和字串
陣列的宣告與遍歷
$fruits = ["apple", "banana", "orange"]; foreach ($fruits as $fruit) { echo $fruit; }
字串運算
$str = "Hello, PHP!"; echo strlen($str); // 输出:12 echo strtoupper($str); // 输出:HELLO, PHP! echo substr($str, 7); // 输出:PHP!
三、資料庫操作
$servername = "localhost"; $username = "root"; $password = "123456"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . 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 "Name: " . $row['name'] . ", Age: " . $row['age']; } } else { echo "No results found."; }
$sql = "INSERT INTO users (name, age) VALUES ('John', 25)"; if (mysqli_query($conn, $sql)) { echo "Data inserted successfully."; } else { echo "Error: " . mysqli_error($conn); }
class Car { public $color; public function drive() { echo "Driving..."; } } $car = new Car(); $car->color = "red"; $car->drive();
class SportsCar extends Car { public function drive() { echo "Driving at high speed!"; } } $sportsCar = new SportsCar(); $sportsCar->color = "blue"; $sportsCar->drive();
<form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form>
$targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["file"]["name"]); if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) { echo "File uploaded successfully."; } else { echo "Error uploading file."; }
$hashedPassword = password_hash($password, PASSWORD_DEFAULT); $sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashedPassword')"; if (mysqli_query($conn, $sql)) { echo "Registration successful. You can now login."; } else { echo "Error: " . mysqli_error($conn); }
$sql = "SELECT * FROM users WHERE username = '$username'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); if (password_verify($password, $row['password'])) { echo "Login successful."; } else { echo "Password incorrect."; } } else { echo "Username not found."; }
透過本文的介紹和實例程式碼,希望讀者能夠從PHP的基礎知識開始,逐步深入了解PHP的各個方面,從而掌握PHP的高階應用技巧,提升自己的開發能力。同時,也歡迎讀者在實務上探索更多有趣且創新的PHP應用。
以上是深入了解PHP:從入門到精通的詳細內容。更多資訊請關注PHP中文網其他相關文章!