8-Marks PHP
8-Marks PHP
Installation on Windows
1) Download PHP:
o Go to the PHP downloads page.
o Download the latest PHP version suitable for Windows.
2) Extract PHP:
o Extract the downloaded ZIP file to a directory, e.g.,
C:\php.
3) Configure Environment Variables:
o Right-click on 'This PC' or 'Computer' on the desktop and
select 'Properties.'
o Click on 'Advanced system settings,' then 'Environment
Variables.'
o In the 'System variables' section, find and select the 'Path'
variable, then click 'Edit.'
o Add the path to the PHP directory (e.g., C:\php) to the list
of paths.
4) Configure PHP:
o Go to the PHP directory and rename php.ini-development
to php.ini.
o Open php.ini with a text editor and configure it as needed.
Common changes include:
▪ Setting extension_dir to the path of the ext directory
within your PHP directory.
▪ Enabling extensions such as extension=curl,
extension=mbstring, etc.
5) Verify Installation:
o Open a command prompt and type php -v to verify PHP is
installed correctly.
• echo: This PHP command outputs the text and variables to the
webpage.
• date("format"): This function returns the current date and time
formatted according to the specified format string.
o l: Full textual representation of the day of the week.
o F: Full textual representation of the month.
o j: Day of the month without leading zeros.
o Y: 4-digit year.
o A: Uppercase AM or PM.
• Logical Operators:
These are basically used to operate with conditional statements
and expressions. Conditional statements are based on
conditions.
Symbol Name Syntax
or Logical OR $x or $y
|| Logical OR $x || $y
• Assignment Operators:
These operators are used to assign values to different variables,
with or without mid-operations.
Operator Name Syntax
= Assign $x = $y
+= Add then assign $x += $y
-= Subtract then assign $x -= $y
*= Multiply then $x *= $y
assign
/= Divide then assign $x /= $y
%= Divide then assign $x %= $y
• Increment/Decrement Operators
Operator Name Syntax
++ Pre-Increment ++$x
-- Pre-Decrement --$x
++ Post-Increment $x++
-- Post-Decrement $x--
• String Operators
Operator Name Syntax
. Concatenation $x.$y
Creating Arrays:
1. Indexed Arrays: These use numeric keys.
$fruits = array("Apple", "Banana", "Orange");
$fruits = ["Apple", "Banana", "Orange"];
2. Associative Arrays: These use named keys.
$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
$age = ["Peter" => 35, "Ben" => 37, "Joe" => 43];
2. Associative Arrays:
echo $age["Peter"]; // Outputs: 35
3. Multidimensional Arrays:
echo $cars[0][0]; // Outputs: Volvo
echo $cars[1][2]; // Outputs: 13
Manipulating Arrays:
1. Adding Elements:
$fruits[] = "Grapes";
$age["Sam"] = 25;
2. Modifying Elements:
$fruits[0] = "Cherry";
$age["Peter"] = 36;
3. Removing Elements:
unset($fruits[1]);
unset($age["Ben"]);
Example:
Let's look at an example where we cast different types of variables:
php
<?php
$var1 = "123"; // String
$var2 = 456.78; // Float
$var3 = "true"; // String
$int_var = (int)$var1; // Cast to integer
$float_var = (float)$var2; // Cast to float (though it is already a
float)
$bool_var = (bool)$var3; // Cast to boolean
echo "Original \$var1 (string): $var1\n";
echo "Casted \$int_var (integer): $int_var\n";
echo "Original \$var2 (float): $var2\n";
echo "Casted \$float_var (float): $float_var\n";
echo "Original \$var3 (string): $var3\n";
echo "Casted \$bool_var (boolean): $bool_var\n";
?>
Output:
Original $var1 (string): 123
Casted $int_var (integer): 123
Original $var2 (float): 456.78
Casted $float_var (float): 456.78
Original $var3 (string): true
Casted $bool_var (boolean): 1
Explanation:
1. Casting String to Integer:The string "123" is cast to the integer 123.
2. Casting Float to Float:The float 456.78 remains as 456.78 since it is
already a float.
3. Casting String to Boolean: The string "true" is cast to the boolean
true (which is represented as 1 in the output).
1. strlen()
Purpose: Returns the length of a string.
Example:
$string = "Hello, World!";
$length = strlen($string);
echo "The length of the string is: $length"; // Output: The length of
the string is: 13
2. array_merge()
Purpose: Merges one or more arrays into one array.
Example:
$array1 = ["apple", "banana"];
$array2 = ["cherry", "date"];
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);
// Output: Array ( [0] => apple [1] => banana [2] => cherry [3] =>
date )
3. strpos():
Purpose: Finds the position of the first occurrence of a substring in a
string.
Example:
$str = "Hello, world!";
echo strpos($str, "world"); // Outputs: 7
4. array_push():
Purpose: Adds one or more elements to the end of an array.
Example:
$fruits = ["apple", "banana"];
array_push($fruits, "cherry", "date");
print_r($fruits);
// Output: Array ( [0] => apple [1] => banana [2] => cherry [3] =>
date )
5. strcmp()
Purpose: Compares two strings.
Example:
$str1 = "apple";
$str2 = "banana";
echo strcmp($str1, $str2); // Outputs: -1
sql
CREATE DATABASE test_db;
USE test_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
3. Inserting Data:
To insert data into the users table:
<?php
$name = 'John Doe';
$email = 'john.doe@example.com';
$sql = "INSERT INTO users (name, email) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$name, $email]);
echo "New record created successfully";
?>
4. Fetching Data:
To fetch data from the users table:
<?php
$sql = "SELECT * FROM users";
$stmt = $pdo->query($sql);
while ($row = $stmt->fetch()) {
echo $row['id'] . " - " . $row['name'] . " - " . $row['email'] . "<br>";
}
?>
5. Updating Data:
To update data in the users table:
<?php
$id = 1;
$newEmail = 'new.email@example.com';
$sql = "UPDATE users SET email = ? WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$newEmail, $id]);
echo "Record updated successfully";
?>
6. Deleting Data:
To delete data from the users table:
<?php
$id = 1;
$sql = "DELETE FROM users WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
echo "Record deleted successfully";
?>
Using mysqli:
php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
Using PDO
php
$dsn = 'mysql:host=localhost;dbname=database';
$username = 'username';
$password = 'password';
try {
$conn = new PDO($dsn, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
2. Creating a Database:
Using mysqli
php
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
Using PDO:
php
$sql = "CREATE DATABASE myDB";
$conn->exec($sql);
echo "Database created successfully";
3. Creating a Table:
Using mysqli
php
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
Using PDO:
php
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$conn->exec($sql);
echo "Table MyGuests created successfully";
4. Inserting Data:
Using mysqli
php
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Using PDO:
php
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
$conn->exec($sql);
echo "New record created successfully";
5. Selecting Data:
Using mysqli
php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
Using PDO:
php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
foreach ($conn->query($sql) as $row) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " .
$row["lastname"] . "<br>";
}
6. Updating Data:
Using mysqli
php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
Using PDO:
php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "Record updated successfully";
7.Deleting Data:
Using mysqli
php
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
Using PDO:
php
$sql = "DELETE FROM MyGuests WHERE id=3";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "Record deleted successfully";
1. Establish a Connection
First, connect to the MySQL database using the mysqli or PDO
extension. Here's an example using mysqli:
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);
}
2. Execute a Query
You can execute different types of queries such as SELECT, INSERT,
UPDATE, and DELETE using the query method.
SELECT Query
php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
INSERT Query
php
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
UPDATE Query
php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
DELETE Query
php
$sql = "DELETE FROM MyGuests WHERE id=3";