CH 6
CH 6
Let's cover Unit 6: PHP and MySQL concisely, focusing on the core concepts for your oral
exam.
3. Program Flow
Controls the order in which statements are executed.
• Conditional Statements:
• if, else if, else: Execute code based on a condition.
• switch: Execute different blocks of code based on a single value.
• Looping Statements:
• for: Loops a specific number of times.
• while: Loops as long as a condition is true.
• do...while: Loops at least once, then as long as a condition is true.
• foreach: Specifically for iterating over arrays.
• Control Statements:
• break: Exits a loop or switch statement.
• continue: Skips the rest of the current loop iteration and proceeds to the next.
4. Functions
• Basics: Reusable blocks of code that perform a specific task.
• Definition: Declared using the function keyword.
• Parameters & Arguments: Functions can accept input values (parameters) and return a
value.
• Return Value: return keyword sends a value back from the function.
• User-defined Functions: Functions created by the developer.
• Built-in Functions: PHP provides a vast library of pre-defined functions (e.g., strlen(),
date(), explode(), isset()).
• Example:
PHP
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("World"); // Output: Hello, World!
?>
• Databases:
• PHP is widely used to interact with databases to store, retrieve, update, and delete
data.
• MySQL: A popular open-source relational database management system (RDBMS)
that integrates seamlessly with PHP.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " -
Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$stmt->close();
$conn->close();
?>