Detailed Viva Notes on PHP & MySQL
1. Introduction to PHP
• PHP: Stands for "PHP: Hypertext Preprocessor," a server-side scripting language
used for web development.
• Key Features:
o Cross-platform compatibility.
o Open-source.
o Database integration, especially with MySQL.
o Embeddable in HTML.
• History:
o Created in 1994 by Rasmus Lerdorf.
o PHP 7 introduced significant speed and memory improvements.
2. Basic Syntax of PHP
• PHP Tags: <?php ... ?>
• Comments:
o Single-line: // or #
o Multi-line: /* ... */
• Variables: Start with $ (e.g., $name = "John";)
• Data Types: Strings, Integers, Floats, Booleans, Arrays, Objects, NULL.
• Operators: Arithmetic (+, -), Logical (&&, ||), Comparison (==, !=).
3. Defining Variables and Constants
• Variables: Dynamic, case-sensitive.
• Constants:
o Declared using define("NAME", "Value");
o Immutable and global.
• Magic Constants: __FILE__, __LINE__, etc.
4. Control Structures
• Decision Making:
o if, if-else, if-elseif-else.
o switch.
• Loops:
o for, while, do-while, foreach.
o Break: Exit loop.
o Continue: Skip iteration.
5. Functions in PHP
• Syntax:
php
Copy code
function functionName($param) {
// code
}
• Call by Value: Passes a copy.
• Call by Reference: Passes a reference using &.
• Default Parameters: function greet($name = "Guest").
6. Arrays in PHP
• Types: Indexed, Associative, Multidimensional.
• Creating Arrays:
php
Copy code
$arr = array("one", "two");
$assoc = array("key" => "value");
• Accessing: $arr[0], $assoc["key"].
7. Strings
• Creating Strings: Single (') and double (") quotes.
• String Functions:
o strlen(), strpos(), str_replace(), substr().
o trim(), strtolower(), strtoupper().
8. Recursive Functions
• Example: Factorial calculation.
php
Copy code
function factorial($n) {
return ($n == 0) ? 1 : $n * factorial($n - 1);
}
9. Mixing PHP and HTML
• Embed PHP inside HTML for dynamic content generation. Example:
php
Copy code
<h1><?php echo "Dynamic Title"; ?></h1>
These notes encapsulate the essential points for PHP & MySQL viva preparation. Let me
know if you need specific elaboration!
4o
You said:
that's it??
ChatGPT said:
ChatGPT
Here’s an extended set of viva notes for PHP & MySQL, covering more in-depth concepts
and additional topics from the uploaded file.
1. PHP: Introduction & Key Features
• Full Form: PHP: Hypertext Preprocessor.
• Purpose: Server-side scripting for dynamic web page creation.
• Key Advantages:
o Platform Independent: Runs on Linux, Windows, macOS, etc.
o Open-Source: Large community and free to use.
o Database Integration: Strong support for MySQL.
o Fast Execution: Efficient for web applications.
• History Timeline:
o 1994: Personal Home Page (PHP Tools).
o 2000: PHP 4 (Zend Engine).
o 2015: PHP 7 (Speed improvements with Zend Engine 3).
2. PHP Syntax
• Tags: <?php ... ?>.
• Echo Statement: Outputs content, e.g., echo "Hello, World!";.
• Variables:
o Start with $, e.g., $name = "John";.
o Loosely typed (data type inferred from context).
3. Constants & Variables
• Constants: Immutable values defined with define("NAME", "Value").
• Magic Constants:
o __FILE__: Current file.
o __LINE__: Line number in the file.
• Scope:
o Global: Defined outside functions.
o Local: Inside functions.
o Superglobals: Built-in variables accessible anywhere (e.g., $_GET, $_POST).
4. Control Structures
Decision Making:
• If Statement:
php
Copy code
if ($x > 5) {
echo "X is greater!";
}
• Switch Case:
php
Copy code
switch ($day) {
case 1: echo "Monday"; break;
default: echo "Other Day";
}
Loops:
• While Loop:
php
Copy code
while ($x < 10) {
echo $x++;
}
• For Loop:
php
Copy code
for ($i = 0; $i < 10; $i++) {
echo $i;
}
5. Functions
• User-Defined Functions:
php
Copy code
function greet($name) {
return "Hello, $name!";
}
echo greet("John");
• Default Parameters: function hello($name = "Guest").
• Call by Reference:
php
Copy code
function increment(&$num) { $num++; }
• Recursive Function Example (Factorial):
php
Copy code
function factorial($n) {
return ($n == 0) ? 1 : $n * factorial($n - 1);
}
6. Arrays
• Types:
o Indexed: $arr = array(1, 2, 3);.
o Associative: $assoc = array("name" => "John");.
o Multidimensional:
php
Copy code
$matrix = array(
array(1, 2),
array(3, 4)
);
echo $matrix[0][1]; // 2
• Operations:
o Accessing: $arr[0];
o Looping:
php
Copy code
foreach ($arr as $val) { echo $val; }
7. Strings
Basic Operations:
• Concatenation: $str = "Hello" . " World!";.
• Access Characters: $str[0]; (First character).
String Functions:
• Length: strlen("Hello"); // Outputs 5.
• Substring: substr("Hello", 1, 3); // "ell".
• Replace:
php
Copy code
$newStr = str_replace("World", "PHP", "Hello World!");
• Formatting:
php
Copy code
printf("Number: %.2f", 12.3456); // Outputs 12.35
8. File Inclusion
• Include: Includes code from another file.
php
Copy code
include 'header.php';
• Require: Similar to include, but halts script if the file is missing.
9. MySQL Integration
• Connecting to Database:
php
Copy code
$conn = new mysqli("localhost", "root", "", "test_db");
if ($conn->connect_error) { die("Connection failed"); }
• Executing Queries:
php
Copy code
$result = $conn->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo $row["name"];
}
10. Advanced Topics
Sessions and Cookies:
• Start Session:
php
Copy code
session_start();
$_SESSION["user"] = "John";
• Cookies:
php
Copy code
setcookie("user", "John", time() + (86400 * 30), "/");
Error Handling:
• Try-Catch Block:
php
Copy code
try {
// Code
} catch (Exception $e) {
echo $e->getMessage();
}
11. Important Viva Questions
1. What is PHP? How does it differ from client-side languages like JavaScript?
2. Explain the different types of arrays in PHP.
3. What are Superglobals? Give examples.
4. Demonstrate file handling in PHP.
5. How does PHP connect with MySQL databases?
6. What are the differences between include and require?
7. Explain the concept of recursion with an example.
8. How are sessions and cookies different?
These notes aim to cover the theoretical and practical aspects necessary for PHP & MySQL
viva exams. Let me know if you need more!
4o
You said:
Important Viva Questions What is PHP? How does it differ from client-side languages like
JavaScript? Explain the different types of arrays in PHP. What are Superglobals? Give
examples. Demonstrate file handling in PHP. How does PHP connect with MySQL
databases? What are the differences between include and require? Explain the concept of
recursion with an example. How are sessions and cookies different? answer these
ChatGPT said:
ChatGPT
Important Viva Questions with Answers
1. What is PHP? How does it differ from client-side languages like
JavaScript?
• PHP: PHP (Hypertext Preprocessor) is a server-side scripting language used for
dynamic web development and interacting with databases.
• Differences:
o Execution:
▪ PHP: Runs on the server; output is sent to the browser as HTML.
▪ JavaScript: Runs in the browser (client-side).
o Usage:
▪ PHP: Handles backend tasks like database queries, session
management.
▪ JavaScript: Handles frontend tasks like form validation, animations.
o Visibility:
▪ PHP code is hidden from the user.
▪ JavaScript code is visible to the user via "View Page Source."
2. Explain the different types of arrays in PHP.
1. Indexed Arrays:
o Elements have numeric indices starting from 0.
php
Copy code
$arr = array("Apple", "Banana", "Cherry");
echo $arr[1]; // Outputs: Banana
2. Associative Arrays:
o Uses named keys instead of numeric indices.
php
Copy code
$assoc = array("name" => "John", "age" => 25);
echo $assoc["name"]; // Outputs: John
3. Multidimensional Arrays:
o Arrays within arrays.
php
Copy code
$matrix = array(
array(1, 2),
array(3, 4)
);
echo $matrix[1][0]; // Outputs: 3
3. What are Superglobals? Give examples.
• Superglobals: Built-in PHP variables that are accessible globally, regardless of scope.
• Examples:
o $_GET: Data sent via URL parameters.
o $_POST: Data sent via HTML forms (POST method).
o $_SESSION: Stores session variables.
o $_COOKIE: Contains cookies sent by the server to the client.
o $_SERVER: Contains information like headers, paths, and script locations.
4. Demonstrate file handling in PHP.
• Opening a File:
php
Copy code
$file = fopen("example.txt", "r"); // Open in read mode
• Reading a File:
php
Copy code
while (!feof($file)) {
echo fgets($file); // Reads line by line
}
fclose($file); // Close the file
• Writing to a File:
php
Copy code
$file = fopen("example.txt", "w");
fwrite($file, "This is a new line.");
fclose($file);
5. How does PHP connect with MySQL databases?
• Using MySQLi (Object-Oriented):
php
Copy code
$conn = new mysqli("localhost", "root", "", "test_db");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
• Executing Queries:
php
Copy code
$result = $conn->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo $row["name"];
}
$conn->close();
6. What are the differences between include and require?
Aspect include require
Behavior on
Issues a warning; script continues. Issues a fatal error; script stops.
Error
Optional files or non-critical Mandatory files or critical
Usage
components. components.
Example include 'file.php'; require 'file.php';
7. Explain the concept of recursion with an example.
• Recursion: A function calls itself to solve a smaller instance of the same problem
until a base condition is met.
• Example (Factorial Calculation):
php
Copy code
function factorial($n) {
if ($n == 0) {
return 1; // Base case
}
return $n * factorial($n - 1); // Recursive call
}
echo factorial(5); // Outputs: 120
8. How are sessions and cookies different?
Aspect Session Cookie
Storage Server-side. Client-side (browser).
Lifetime Ends when browser is closed (default). Can persist based on expiry time.
Security More secure; not visible to the user. Less secure; stored in plaintext.
Usage Store sensitive data like login info. Store non-sensitive preferences.
Examples
• Start session:
php
Copy code
session_start();
$_SESSION["user"] = "John";
• Set cookie:
php
Copy code
setcookie("user", "John", time() + (86400 * 30), "/");
Let me know if you need further explanations!
4o
You said:
string operations in php
ChatGPT said:
ChatGPT
String Operations in PHP
PHP provides a variety of operations for working with strings. Here's a detailed overview:
1. String Creation
• Single Quotes ('): Treats content literally.
php
Copy code
$str = 'This is a string.';
echo 'Name: $str'; // Outputs: Name: $str
• Double Quotes ("): Allows variable interpolation and escape sequences.
php
Copy code
$name = "John";
echo "Hello, $name!"; // Outputs: Hello, John!
2. Concatenation
• Use the . operator to join strings.
php
Copy code
$str1 = "Hello";
$str2 = "World";
echo $str1 . " " . $str2; // Outputs: Hello World
3. Accessing Characters
• Treat strings like arrays to access individual characters.
php
Copy code
$str = "PHP";
echo $str[0]; // Outputs: P
echo $str[1]; // Outputs: H
4. String Functions
a. String Length
• strlen(): Returns the number of characters in a string.
php
Copy code
$str = "Hello";
echo strlen($str); // Outputs: 5
b. Substring Extraction
• substr(): Extracts a portion of a string.
php
Copy code
$str = "Hello, World!";
echo substr($str, 7, 5); // Outputs: World
c. Search and Replace
• strpos(): Finds the first occurrence of a substring.
php
Copy code
$str = "Hello, World!";
echo strpos($str, "World"); // Outputs: 7
• str_replace(): Replaces all occurrences of a substring.
php
Copy code
$str = "Hello, World!";
echo str_replace("World", "PHP", $str); // Outputs: Hello, PHP!
d. String Case Conversion
• strtolower(): Converts to lowercase.
• strtoupper(): Converts to uppercase.
• ucfirst(): Capitalizes the first character.
• ucwords(): Capitalizes the first character of each word.
php
Copy code
$str = "hello world";
echo strtoupper($str); // Outputs: HELLO WORLD
echo ucwords($str); // Outputs: Hello World
e. Trimming Strings
• trim(): Removes whitespace from both ends.
• ltrim(): Removes whitespace from the left.
• rtrim(): Removes whitespace from the right.
php
Copy code
$str = " Hello ";
echo trim($str); // Outputs: Hello
f. Reversing a String
• strrev(): Reverses the string.
php
Copy code
$str = "Hello";
echo strrev($str); // Outputs: olleH
g. Explode and Implode
• explode(): Splits a string into an array.
php
Copy code
$str = "apple,banana,cherry";
$arr = explode(",", $str);
print_r($arr); // Outputs: Array ( [0] => apple [1] => banana [2] =>
cherry )
• implode(): Joins array elements into a string.
php
Copy code
$arr = ["apple", "banana", "cherry"];
echo implode("-", $arr); // Outputs: apple-banana-cherry
h. Formatting Strings
• printf(): Outputs a formatted string.
• sprintf(): Returns a formatted string.
php
Copy code
$num = 123.456;
printf("Formatted number: %.2f", $num); // Outputs: Formatted
number: 123.46
i. Comparing Strings
• strcmp(): Case-sensitive comparison.
• strcasecmp(): Case-insensitive comparison.
php
Copy code
$str1 = "Hello";
$str2 = "hello";
echo strcmp($str1, $str2); // Outputs: non-zero value
echo strcasecmp($str1, $str2); // Outputs: 0
5. Multibyte String Functions (UTF-8 Support)
For working with multibyte strings (e.g., UTF-8 characters), use mb_* functions.
• mb_strlen(): Length of multibyte string.
• mb_substr(): Extract substring from multibyte string.
php
Copy code
$str = "こんにちは"; // Japanese for "Hello"
echo mb_strlen($str); // Outputs: 5
6. Escaping Characters
• Use addslashes() to escape quotes for database queries.
php
Copy code
$str = "It's a test.";
echo addslashes($str); // Outputs: It\'s a test.
Common Example
php
Copy code
$str = " PHP is great! ";
// Remove whitespace
$trimmed = trim($str);
// Convert to uppercase
$upper = strtoupper($trimmed);
// Replace word
$replaced = str_replace("GREAT", "awesome", $upper);
echo $replaced; // Outputs: PHP IS AWESOME!
Let me know if you need further elaboration or examples!
4o
You said:
array operation in php
ChatGPT said:
ChatGPT
Array Operations in PHP
PHP provides extensive functionality for working with arrays. Below is a comprehensive
guide to array operations:
1. Creating Arrays
• Indexed Array:
php
Copy code
$arr = array("Apple", "Banana", "Cherry");
$arr2 = ["Dog", "Cat", "Rabbit"]; // Alternative
• Associative Array:
php
Copy code
$assoc = array("name" => "John", "age" => 25);
• Multidimensional Array:
php
Copy code
$multi = array(
array(1, 2, 3),
array(4, 5, 6)
);
2. Accessing Array Elements
• Indexed Array:
php
Copy code
echo $arr[0]; // Outputs: Apple
• Associative Array:
php
Copy code
echo $assoc["name"]; // Outputs: John
• Multidimensional Array:
php
Copy code
echo $multi[1][2]; // Outputs: 6
3. Modifying Arrays
• Add Elements:
php
Copy code
$arr[] = "Orange"; // Adds to the end of the array
$assoc["city"] = "New York"; // Adds new key-value pair
• Change Elements:
php
Copy code
$arr[1] = "Mango"; // Changes "Banana" to "Mango"
$assoc["age"] = 30; // Updates age to 30
4. Array Functions
a. Array Size and Check
• count(): Returns the number of elements in an array.
php
Copy code
echo count($arr); // Outputs: 4
• is_array(): Checks if a variable is an array.
php
Copy code
echo is_array($arr); // Outputs: 1 (true)
b. Adding and Removing Elements
• Push (Add to End): array_push()
php
Copy code
array_push($arr, "Pineapple");
• Pop (Remove from End): array_pop()
php
Copy code
$last = array_pop($arr); // Removes "Pineapple"
• Shift (Remove from Start): array_shift()
php
Copy code
$first = array_shift($arr); // Removes "Apple"
• Unshift (Add to Start): array_unshift()
php
Copy code
array_unshift($arr, "Strawberry");
c. Merging and Slicing
• array_merge(): Combines two or more arrays.
php
Copy code
$merged = array_merge($arr, $arr2);
• array_slice(): Extracts a portion of an array.
php
Copy code
$slice = array_slice($arr, 1, 2); // Extracts 2 elements starting
from index 1
d. Searching
• in_array(): Checks if a value exists in an array.
php
Copy code
echo in_array("Banana", $arr); // Outputs: 1 (true)
• array_search(): Returns the index/key of the searched value.
php
Copy code
echo array_search("Mango", $arr); // Outputs: 1
e. Sorting
• sort(): Sorts an array in ascending order.
php
Copy code
sort($arr); // Alphabetical order
• rsort(): Sorts in descending order.
php
Copy code
rsort($arr);
• asort(): Sorts an associative array by values while maintaining keys.
php
Copy code
asort($assoc);
• ksort(): Sorts an associative array by keys.
php
Copy code
ksort($assoc);
f. Array Keys and Values
• array_keys(): Returns an array of keys.
php
Copy code
$keys = array_keys($assoc); // Outputs: ["name", "age"]
• array_values(): Returns an array of values.
php
Copy code
$values = array_values($assoc); // Outputs: ["John", 30]
g. Flipping and Reversing
• array_reverse(): Reverses the order of an array.
php
Copy code
$reversed = array_reverse($arr);
• array_flip(): Exchanges keys with values.
php
Copy code
$flipped = array_flip($assoc); // Outputs: ["John" => "name", 30 =>
"age"]
5. Iterating Through Arrays
• For Loop (Indexed Array):
php
Copy code
for ($i = 0; $i < count($arr); $i++) {
echo $arr[$i];
}
• Foreach Loop:
php
Copy code
foreach ($assoc as $key => $value) {
echo "$key: $value";
}
6. Array Operations
Array Diff
• array_diff(): Finds the difference between two arrays.
php
Copy code
$arr1 = ["A", "B", "C"];
$arr2 = ["B", "C", "D"];
$diff = array_diff($arr1, $arr2); // Outputs: ["A"]
Array Intersect
• array_intersect(): Finds common elements.
php
Copy code
$common = array_intersect($arr1, $arr2); // Outputs: ["B", "C"]
7. Multidimensional Array Operations
• Accessing:
php
Copy code
$multi[0][1]; // Outputs: 2
• Iterating:
php
Copy code
foreach ($multi as $row) {
foreach ($row as $val) {
echo $val;
}
}
8. Example: Practical Array Operations
php
Copy code
$fruits = array("Apple", "Banana", "Cherry");
// Add new fruit
array_push($fruits, "Orange");
// Sort the array
sort($fruits);
// Search for a value
if (in_array("Banana", $fruits)) {
echo "Banana is in the array.";
}
// Merge with another array
$vegetables = array("Carrot", "Potato");
$merged = array_merge($fruits, $vegetables);
print_r($merged);
Let me know if you need more examples or explanations!
4o
You said:
loops in php difference in table form
ChatGPT said:
ChatGPT
Loops in PHP: Comparison Table
Loop Condition
Syntax Use Case Key Features
Type Check
- Best for fixed
iterations.
for for (initialization; - Combines
condition;
Known number of Before each
Loop initialization,
increment) iterations. iteration.
condition, and
increment in one
line.
while - Flexible for
while (condition) { Loop until a Before each
Loop // Code } conditions where
condition is true. iteration.
iteration count is
Loop Condition
Syntax Use Case Key Features
Type Check
unknown.
- May not execute if
the condition is false
initially.
- Executes code at
Ensure code
least once before
do- executes at least
while do { // Code } while After each checking the
(condition); once, even if the
Loop iteration. condition.
condition is initially
- Suitable for post-
false.
condition loops.
- Automatically
handles array keys
foreach foreach ($array as
Iterating over arrays Iterates
$key => $value) { // and values.
Loop (indexed or through
Code } - Simple syntax for
associative). elements.
working with arrays
or collections.
Examples
1. For Loop:
php
Copy code
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// Output: 1 2 3 4 5
2. While Loop:
php
Copy code
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
// Output: 1 2 3 4 5
3. Do-While Loop:
php
Copy code
$i = 6;
do {
echo $i . " ";
$i++;
} while ($i <= 5);
// Output: 6 (Executes once even though the condition is false)
4. Foreach Loop:
php
Copy code
$arr = ["Apple", "Banana", "Cherry"];
foreach ($arr as $fruit) {
echo $fruit . " ";
}
// Output: Apple Banana Cherry
Let me know if you need further explanations or additional examples!
4o
You said:
sql and php
ChatGPT said:
ChatGPT
SQL and PHP: Integration Overview
PHP and SQL (Structured Query Language) are commonly used together for dynamic web
development. PHP interacts with SQL databases (like MySQL) to store, retrieve, and
manipulate data.
1. Setting Up Database Connection in PHP
Using MySQLi (Object-Oriented):
php
Copy code
$conn = new mysqli("localhost", "root", "", "database_name");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
Using PDO (PHP Data Objects):
php
Copy code
try {
$conn = new PDO("mysql:host=localhost;dbname=database_name", "root",
"");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
2. Basic SQL Operations with PHP
a. Inserting Data
php
Copy code
$sql = "INSERT INTO users (name, email) VALUES ('John Doe',
'[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
b. Retrieving Data
• Using MySQLi:
php
Copy code
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
• Using PDO:
php
Copy code
$sql = "SELECT id, name, email FROM users";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
c. Updating Data
php
Copy code
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
d. Deleting Data
php
Copy code
$sql = "DELETE FROM users WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
3. Prepared Statements
Prevents SQL Injection by using placeholders for values.
Using MySQLi:
php
Copy code
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$name = "John";
$email = "[email protected]";
$stmt->execute();
echo "New record created successfully";
$stmt->close();
Using PDO:
php
Copy code
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (:name,
:email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$name = "John";
$email = "[email protected]";
$stmt->execute();
echo "New record created successfully";
4. Closing Database Connection
php
Copy code
$conn->close(); // For MySQLi
$conn = null; // For PDO
5. Example: Full PHP Script to Interact with MySQL
php
Copy code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert Data
$sql = "INSERT INTO users (name, email) VALUES ('Alice',
'[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br>";
}
// Fetch Data
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email:
" . $row["email"] . "<br>";
}
} else {
echo "No records found";
}
// Close connection
$conn->close();
?>
6. Key SQL Functions in PHP
Function Description
query() Executes an SQL query and returns the result.
prepare() Prepares a query for execution (prevents SQL injection).
bind_param() Binds variables to placeholders in prepared statements.
execute() Executes a prepared statement.
fetch_assoc() Fetches the result row as an associative array.
num_rows Checks the number of rows returned in a result set.
7. Best Practices
• Use Prepared Statements: Prevents SQL injection.
• Sanitize Input: Use htmlspecialchars() for data displayed on the frontend.
• Error Handling: Always check for errors using try-catch or mysqli_error().
• Close Connections: Free up server resources by closing connections when done.