× back

PHP

Introduction to Web Servers

Web servers are fundamental components of the internet infrastructure, responsible for hosting and delivering web content and applications to users worldwide. Understanding the different types of web servers and development environments is crucial for developers and system administrators alike.

Different Types of Web Servers

  • Apache HTTP Server:
    • Apache HTTP Server, commonly known as Apache, is an open-source web server software maintained by the Apache Software Foundation.
    • It is highly versatile and widely used for hosting static and dynamic websites, supporting various features such as virtual hosting, SSL/TLS encryption, URL rewriting, and authentication mechanisms.
    • Apache is compatible with multiple operating systems, including Linux, Unix, macOS, and Windows, making it a preferred choice for a broad range of web hosting scenarios.
  • Tomcat and Glassfish:
    • Tomcat and Glassfish are Java-based application servers designed to execute Java servlets and render JavaServer Pages (JSP).
    • Apache Tomcat, often referred to simply as Tomcat, is a lightweight and robust servlet container used for deploying Java web applications. It provides support for servlets, JSP, and WebSocket implementations.
    • Glassfish, developed by Oracle Corporation, offers a complete Java EE (Enterprise Edition) environment with additional features such as Java Messaging Service (JMS), Java Persistence API (JPA), and Enterprise JavaBeans (EJBs). It is suitable for enterprise-level Java web applications requiring advanced functionalities.
  • IIS (Internet Information Services):
    • Internet Information Services (IIS) is a web server developed by Microsoft for Windows Server environments.
    • It is commonly used to host websites and applications built using Microsoft technologies such as ASP.NET, C#, and Visual Basic.NET.
    • IIS offers features like integrated security, application pools for managing web applications, and performance monitoring tools through its management console.
  • Nginx (Engine X):
    • Nginx is a high-performance, lightweight, and open-source web server known for its efficient handling of concurrent connections and low resource consumption.
    • It excels in serving static content, acting as a reverse proxy, load balancer, and caching server.
    • Nginx is often used in modern web architectures alongside Apache or other servers to improve performance, scalability, and security.

Development Environments:

Development environments play a crucial role in the software development lifecycle, providing developers with tools and resources to create, test, and debug web applications effectively. These environments often include web servers, databases, scripting languages, and other development tools necessary for building and deploying web projects.

Following are the development environment stacks commonly used:

  1. XAMPP (Cross-Platform Apache, MySQL, PHP, Perl):
    • Cross-Platform: XAMPP supports multiple operating systems, making it accessible to developers using different platforms.
    • Apache HTTP Server: The Apache web server component handles HTTP requests and serves web content.
    • MySQL: A relational database management system used for data storage and retrieval in web applications.
    • PHP: A server-side scripting language that enables dynamic content generation and processing in web applications.
    • Perl: Another scripting language included in XAMPP for server-side development.
  2. WAMP (Windows, Apache, MySQL, PHP/Perl/Python):
    • WAMP is a development stack specifically designed for Windows environments, providing a local server environment for web development.
    • Windows: The operating system where WAMP is installed, offering a familiar environment for Windows-based developers.
    • Apache: The Apache HTTP Server serves as the web server component, handling HTTP requests and serving web content.
    • MySQL (or MariaDB): A relational database management system used for data storage and retrieval.
    • PHP/Perl/Python: Scripting languages that enable server-side processing and dynamic content generation in web applications.

Introduction to PHP

Features of PHP:

  • Performance: PHP scripts execute faster than languages like ASP and JSP. PHP utilizes its own memory management, reducing server workload and minimizing loading times for web pages.
  • Open Source: PHP's source code and software are freely available, allowing developers to access and modify the language according to their needs. All PHP versions and components are downloadable and usable at no cost.
  • Embeddable: PHP code can be seamlessly embedded within HTML tags and scripts, enabling developers to create dynamic and interactive web pages.
  • Platform Independence: PHP is compatible with various operating systems such as Unix, macOS, Windows, and Linux. Applications developed in PHP on one operating system can easily run on other platforms, enhancing cross-platform compatibility.
  • Error Handling: PHP includes predefined error reporting mechanisms that generate notices or warnings during runtime, aiding developers in identifying and resolving errors in their code.
  • Weakly Typed Language: PHP is a weakly typed or loosely typed language, allowing variables to be used without declaring their data types. The type of data and its value determine the variable's type during execution.
  • File Storage: PHP uses different directories for file storage, such as 'htdocs' for XAMPP and 'www' for WAMP. Developers must create these folders to organize and store PHP files and resources effectively.

Syntax

  • PHP uses a combination of HTML, JavaScript-like syntax, and PHP-specific tags to execute server-side code.
                    
<? php 
    echo "PHP";
?>
                    
                
  • In the above code, we have used PHP opening and closing tags <?php ?> to encapsulate PHP code. The echo statement is used to output the text "PHP" to the webpage.

File Extension

  • PHP files typically use the .php extension, indicating that the file contains PHP code that needs to be processed by the PHP interpreter on the server.

Running PHP Scripts Locally

  1. Install XAMPP or WAMP:
    • Download and install XAMPP or WAMP on your computer.
    • Follow the installation instructions provided by the respective software.
  2. Start the Local Server:
    • Open XAMPP Control Panel or WAMP Manager.
    • Start the Apache server from the control panel or manager.
    • Or go to the terminal, change the directory to /opt/lampp, and run "sudo ./xampp start". This works in Linux."
  3. Create or Place Your PHP File:
    • Navigate to the directory where PHP files should be placed (e.g., htdocs for XAMPP, www for WAMP).
    • Create a new PHP file (e.g., abc.php) or place an existing PHP file in this directory.
  4. Accessing the PHP File:
    • Open your web browser (e.g., Chrome, Firefox).
    • In the address bar, type http://localhost/abc.php (replace abc.php with your PHP file name).
    • If using a different port, specify the port in the URL (e.g., http://localhost:8080/abc.php).
  5. Execute the PHP Script:
    • The local server will process the PHP script and display the output in your web browser.
    • Errors, if any, will be displayed on the page or in server logs.

PHP Programming

echo

  • `echo` can be used to print strings, multi-line strings, escape characters, variables, etc. Some important points that you must know about the `echo` statement are:
    1. `echo` is a statement used to display output.
    2. `echo` can be used with or without parentheses: `echo` or `echo()`.
    3. `echo` does not return any value.
    4. You can pass multiple strings separated by commas (,) in `echo`.
    5. `echo` is faster than the `print` statement.

Example:

                    
<?php
    echo "Hello World";
?>
                    
                
  • Just like `echo`, we also have the `print` statement which does the exact same thing as `echo`. The difference is that `echo` doesn't return any value, but the `print` statement always returns an integer value of 1. Additionally, `print` is slower than `echo`.

PHP Variables

In PHP, a variable is declared using a $ sign followed by the variable name. Here are some important points to know about variables:

  • As PHP is a loosely typed language, we do not need to declare the data types of the variables. It automatically analyzes the values and makes conversions to the correct datatype.
  • After declaring a variable, it can be reused throughout the code.
  • The assignment operator (=) is used to assign a value to a variable.

Syntax of declaring a variable in PHP is given below:

                    
$variablename = value;
                    
                

Rules for declaring PHP variables:

  • A variable must start with a dollar ($) sign, followed by the variable name.
  • It can only contain alphanumeric characters and underscores ( A-z, 0-9, _ ).
  • A variable name must start with a letter or underscore (_) character.
  • A PHP variable name cannot contain spaces.
  • The variable name cannot start with a number or special symbols.
  • PHP variables are case-sensitive, so $name and $NAME are treated as different variables.

PHP Variable: Declaring string, integer, and float

Let's see the example to store string, integer, and float values in PHP variables.

    
<?php
    $str = "hello string";
    $x = 200;
    $y = 44.6;
    echo "string is: $str 
"; echo "integer is: $x
"; echo "float is: $y
"; ?>

Sum of two numbers in php

                    
<?php
    $num1 = 5;
    $num2 = 4;
    $sum = $num1 + $num2;
    echo "The sum is = $sum";
?>
                    
                

PHP Data Types

In PHP, data types are used to specify the type of data that variables can hold. PHP supports various data types, each with its own characteristics and usage.

Basic Data Types

  • Integer: Represents whole numbers, such as 1, 100, -5, etc.
  • Float (Floating Point Number): Represents decimal numbers, such as 3.14, -0.5, etc.
  • String: Represents sequences of characters, enclosed in single quotes (' ') or double quotes (" ").
  • Boolean: Represents true or false values.
  • Array: Represents a collection of elements, each identified by a key.
  • Object: Represents instances of user-defined classes, containing properties and methods.
  • Null: Represents a variable with no value assigned.

Special Data Types

  • Resource: Represents external resources, such as file handles or database connections.

Dynamic Typing in PHP

PHP is a loosely typed language known for dynamic typing, meaning you don't need to declare the data type explicitly. PHP determines the data type based on the value assigned to the variable.

Example:

                
$integerVar = 10; // Integer
$floatVar = 3.14; // Float
$stringVar = "Hello, PHP!"; // String
$boolVar = true; // Boolean
$arrayVar = array(1, 2, 3); // Array
$objectVar = new stdClass(); // Object
$nullVar = null; // Null
    

Type Casting

You can also explicitly convert data types using type casting. For example:

                
$intValue = (int) 10.5; // Converts float to integer (10)
$floatValue = (float) "3.14"; // Converts string to float (3.14)
$stringValue = (string) 100; // Converts integer to string ("100")
$boolValue = (bool) ""; // Converts empty string to boolean (false)
    

Control Statements in PHP

Control statements in PHP are used to control the flow of execution in a program. They allow you to make decisions, repeat actions, and perform different tasks based on conditions.

1. Conditional Statements

Conditional statements are used to execute code based on certain conditions. PHP supports the following conditional statements:

  • If Statement: Executes a block of code if a specified condition is true.
  • If...Else Statement: Executes a block of code if a specified condition is true; otherwise, executes another block of code.
  • If...ElseIf...Else Statement: Executes different blocks of code based on multiple conditions.
  • Switch Statement: Executes one block of code among many alternatives based on the value of a variable or expression.

Examples:

Let's see examples of each control statement:

1. If Statement Example

                
$age = 25;
if ($age >= 18) {
    echo "You are eligible to vote.";
}
                
            

2. If...Else Statement Example

                
$marks = 85;
if ($marks >= 60) {
    echo "You passed.";
} else {
    echo "You failed.";
}
                
            

3. If...ElseIf...Else Statement Example

                
$score = 85;
if ($score >= 90) {
    echo "Excellent!";
} elseif ($score >= 70) {
    echo "Good!";
} else {
    echo "Needs improvement.";
}
                
            

4. Switch Statement Example

                
$day = "Monday";
switch ($day) {
    case "Monday":
        echo "Today is Monday.";
        break;
    case "Tuesday":
        echo "Today is Tuesday.";
        break;
    default:
        echo "Invalid day.";
}
                
            

2. Looping Statements

Looping statements are used to execute a block of code repeatedly as long as a specified condition is true. PHP supports the following looping statements:

  • While Loop: Executes a block of code as long as a specified condition is true.
  • Do...While Loop: Executes a block of code once, and then repeats the execution as long as a specified condition is true.
  • For Loop: Executes a block of code a specified number of times.
  • Foreach Loop: Iterates over elements in an array or an object.

Examples:

Let's see examples of each loop:

1. While Loop Example

                
$num = 1;
while ($num <= 5) {
    echo "Number: $num<br>";
    $num++;
}
    

2. Do...While Loop Example

                
$num = 1;
do {
    echo "Number: $num<br>";
    $num++;
} while ($num <= 5);
    

3. For Loop Example

                
for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i<br>";
}
    

4. Foreach Loop Example

                
$fruits = array("Apple", "Banana", "Orange", "Mango");
foreach ($fruits as $fruit) {
    echo "$fruit<br>";
}
    

Arrays in PHP

Arrays in PHP allow you to store multiple values in a single variable. PHP supports several types of arrays:

1. Indexed Arrays

An indexed array stores elements with numeric indices. Elements are accessed using their index numbers.

                
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Outputs: Red
echo $colors[1]; // Outputs: Green
echo $colors[2]; // Outputs: Blue
            
        

2. Associative Arrays

An associative array stores elements with named keys. Elements are accessed using their keys.

                
$person = array("name" => "John", "age" => 30, "city" => "New York");
echo $person["name"]; // Outputs: John
echo $person["age"]; // Outputs: 30
echo $person["city"]; // Outputs: New York
            
        

3. Multidimensional Arrays

A multidimensional array contains one or more arrays. It is used to store arrays within an array.

Associative Array Example:

        
$students = array(
    array("name" => "John", "age" => 20),
    array("name" => "Jane", "age" => 22),
    array("name" => "Doe", "age" => 25)
);
echo $students[0]["name"]; // Outputs: John
echo $students[1]["age"]; // Outputs: 22
        
        

Indexed Array Example:

        
$students = array(
    array("John", 20),
    array("Jane", 22),
    array("Doe", 25)
);
echo $students[0][0]; // Outputs: John
echo $students[1][1]; // Outputs: 22
        
        

Using Array Functions

PHP provides built-in functions to work with arrays, such as count() to count elements in an array and array_push() to add elements to an array.

                
$fruits = array("Apple", "Banana", "Orange");
echo count($fruits); // Outputs: 3

array_push($fruits, "Mango");
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Mango )
            
        

String Handling in PHP

Strings in PHP are sequences of characters, which can include letters, numbers, symbols, and spaces. PHP provides various functions and methods to manipulate and work with strings.

1. Concatenation

Concatenation is the process of combining strings. In PHP, the dot (.) operator is used for concatenation.

                
$name = "John";
$greeting = "Hello, " . $name . "!";
echo $greeting; // Outputs: Hello, John!
    

2. String Length

The strlen() function is used to get the length of a string in PHP.

                
$text = "This is a string.";
echo strlen($text); // Outputs: 16 (including spaces)
    

3. Substrings

The substr() function is used to extract a part of a string.

                
$text = "Hello World";
$substring = substr($text, 0, 5); // Extracts "Hello"
echo $substring;
    

4. String Case

PHP provides functions like strtolower() and strtoupper() to change the case of strings.

                
$text = "Hello World";
echo strtolower($text); // Outputs: hello world
echo strtoupper($text); // Outputs: HELLO WORLD
    

5. String Replace

The str_replace() function is used to replace a substring with another substring in a string.

                
$text = "Hello World";
$newText = str_replace("World", "PHP", $text);
echo $newText; // Outputs: Hello PHP
    

6. String Splitting

PHP provides functions like explode() and implode() to split and join strings based on delimiters.

                
$text = "apple,banana,orange";
$fruitsArray = explode(",", $text); // Splits the string into an array
print_r($fruitsArray); // Outputs: Array ( [0] => apple [1] => banana [2] => orange )

$fruitsString = implode(", ", $fruitsArray); // Joins the array elements into a string
echo $fruitsString; // Outputs: apple, banana, orange
    

Functions in PHP

A function in PHP is a block of reusable code that performs a specific task. Functions help in organizing code, improving readability, and reducing redundancy. Here's how you declare and use functions in PHP:

Basic Syntax:

                
<?php
function functionName($param1, $param2, ...) {
    // Function body
    // Code to be executed when the function is called
    return $returnValue; // Optional: return value
}
?>
                
            

Let's break down the components of a PHP function:

Example 1: Function to Calculate Sum

                
<?php
function calculateSum($num1, $num2) {
    $sum = $num1 + $num2;
    return $sum;
}

$number1 = 10;
$number2 = 5;
$result = calculateSum($number1, $number2);
echo "The sum of $number1 and $number2 is: $result";
?>
                
            

In this example, the calculateSum function takes two parameters and returns their sum.

Example 2: Function to Check Even or Odd

                
<?php
function checkEvenOdd($number) {
    if ($number % 2 == 0) {
        return "Even";
    } else {
        return "Odd";
    }
}

$inputNumber = 15;
$result = checkEvenOdd($inputNumber);
echo "$inputNumber is $result";
?>
                
            

This example demonstrates a function that checks whether a number is even or odd.

Example 3: Function with Default Parameter

                
<?php
function greetUser($name = "Guest") {
    echo "Hello, $name!";
}

greetUser(); // Outputs: Hello, Guest!
greetUser("John"); // Outputs: Hello, John!
?>
                
            

Here, the greetUser function has a default parameter value, allowing it to be called without an argument.

PHP Variable Scope

Variable scope refers to the visibility and accessibility of variables within different parts of a PHP script. Understanding variable scope is crucial for writing efficient and bug-free code. Here are the key aspects of PHP variable scope:

Local Scope

Variables declared within a function have local scope and can only be accessed within that function.

                
<?php
function myFunction() {
    $localVariable = "This is a local variable.";
    echo $localVariable;
}

myFunction(); // Outputs: This is a local variable.
echo $localVariable; // Error: Undefined variable
?>
                
            

Global Scope

Variables declared outside of any function have global scope and can be accessed from anywhere within the script. To access a global variable inside a function, use the global keyword.

                
<?php
$globalVariable = "This is a global variable.";

function myFunction() {
    global $globalVariable;
    echo $globalVariable;
}

myFunction(); // Outputs: This is a global variable.
echo $globalVariable; // Outputs: This is a global variable.
?>
                
            

Static Variables

Static variables retain their values between function calls and are initialized only once. They are useful when you need a variable to persist its value across multiple function calls.

                
<?php
function staticCounter() {
    static $count = 0; // Initialized only once
    $count++;
    echo "Static Count: $count<br>";
}

function regularCounter() {
    $count = 0; // Initialized every time the function is called
    $count++;
    echo "Regular Count: $count<br>";
}

staticCounter(); // Outputs: Static Count: 1
staticCounter(); // Outputs: Static Count: 2
staticCounter(); // Outputs: Static Count: 3

regularCounter(); // Outputs: Regular Count: 1
regularCounter(); // Outputs: Regular Count: 1
regularCounter(); // Outputs: Regular Count: 1
?>
            
        

PHP SuperGlobal Variables

PHP provides several superglobal variables that are used to collect data from various sources. These superglobal variables are accessible from any part of the script, regardless of scope. Here are some of the most commonly used superglobals:

Examples:

Example 1: Using $_POST

This example demonstrates how to use the $_POST variable to collect data from a form.

                
<!-- form.html file --> 
<!DOCTYPE html> 
<html>
    <body> 
        <form method="post" action="post_handler.php">
            <label>Enter your name: </label>
            <input type="text" name="name" />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
                
            
                
<?php
// post_handler.php
$name = $_POST['name'];
echo "Hello, $name!";
?>
                
            

Example 2: Using $_GET

This example demonstrates how to use the $_GET variable to collect data from a form.

                    
<!-- form.html file --> 
<!DOCTYPE html>
<html>
    <body>
        <form action="get_handler.php" method="get">
            Name: <input type="text" name="name">
            <input type="submit" value="Submit">
        </form>
    </body>
</html>
                    
                
                    
<?php
// get_handler.php
$name = $_GET['name'];
echo "Hello, $name!";
?>
                
            

Example 3: Using $_REQUEST

This example demonstrates how to use the $_REQUEST variable to collect data from a form.

                
<!-- form_request.html file --> 
<!DOCTYPE html> 
<html>
    <body> 
        <form method="post" action="request_handler.php">
            <label>Enter your age: </label>
            <input type="text" name="age" />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
                
            
                
<?php
// request_handler.php
$age = $_REQUEST['age'];
echo "Your age is: $age";
?>
                
            

Example 4: Using $_COOKIE

This example demonstrates how to use the $_COOKIE variable to store and retrieve a cookie.

                
<?php
// set_cookie.php
setcookie("user", "John", time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<!DOCTYPE html> 
<html>
    <body> 
        <?php
        if(isset($_COOKIE["user"])) {
            echo "User is " . $_COOKIE["user"];
        } else {
            echo "User is not set";
        }
        ?>
    </body>
</html>
                
            

Example 5: Using $_SESSION

This example demonstrates how to use the $_SESSION variable to store and retrieve session data.

                    
<?php
// start_session.php
session_start();
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
                    
                
                    
<?php
// retrieve_session.php
session_start();
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
                    
                

By understanding and using these superglobal variables, you can effectively manage and manipulate data within your PHP applications.

Program to Add Two Numbers Inputted in an HTML Input Tag and Show the Result in an HTML Input Tag Upon Clicking the Add Button

This example demonstrates how to create a simple web form that allows users to input two numbers, add them, and display the result in another input field using PHP.

                    
<!DOCTYPE html>
<html>
<head>
    <title>Add Two Numbers</title>
</head>
<body>
    <h3>Program to Add Two Numbers Inputted in an HTML Input Tag and Show the Result in an HTML Input Tag Upon Clicking the Add Button</h3>

    <?php
    $sum = ""; // Initialize the sum variable

    // Fetch data directly without checking request method
    $num1 = $_POST["num1"];
    $num2 = $_POST["num2"];
    $sum = $num1 + $num2;
    ?>

    <form method="post" action="">
        <label>Num 1: </label>
        <input type="text" name="num1" value="<?php echo $num1; ?>" required>
        <br>
        <label>Num 2: </label>
        <input type="text" name="num2" value="<?php echo $num2; ?>" required>
        <br>
        <label>Result: </label>
        <input type="text" name="result" value="<?php echo $sum; ?>" >
        <br>
        <input type="submit" value="Add">
        <input type="reset" value="Reset">
    </form>
</body>
</html>
                    
                

Make sure you save this file with ".php" extension.

MySQL Database Connectivity with PHP

MySQL is a popular relational database management system used with PHP for building dynamic web applications. It allows storing, retrieving, and managing structured data efficiently.

Need for Database Connectivity in PHP

Connecting PHP to a MySQL database is essential for web applications that require data storage, retrieval, and manipulation. It enables seamless integration of dynamic content and user data management.

Methods for MySQL Connectivity in PHP

There are three main methods used in PHP to connect to MySQL databases:

  1. MySQL (Deprecated):
    • Deprecated method for MySQL connectivity in PHP.
    • Primarily procedural in nature: In procedural programming, code is written as a series of step-by-step instructions. In the case of MySQL, procedural code involves functions like mysql_connect() and mysql_query() to interact with the database.
    • Supports only MySQL database.
  2. MySQLi (Improved MySQL):
    • Improved version of MySQL connectivity.
    • Supports both procedural and object-oriented approaches:
      • Procedural approach: Similar to MySQL, mysqli allows procedural code where functions like mysqli_connect() and mysqli_query() are used for database operations.
      • Object-oriented approach: In object-oriented programming (OOP), code is organized around objects and classes. In MySQLi's object-oriented mode, you create a connection object (mysqli) and use its methods for database operations. For example, $mysqli = new mysqli("localhost", "username", "password", "database");
    • Exclusive support for MySQL databases.
  3. PDO (PHP Data Objects):
    • PHP's data access abstraction layer.
    • Object-oriented approach for database connectivity:
      • PDO represents a modern and versatile way to interact with databases using OOP principles. You create a PDO object and use its methods for database operations. For example, $pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
    • Supports multiple database systems including MySQL, PostgreSQL, SQLite, etc.

Establishing MySQL Connection in PHP

  • We use a connection string that includes at least three parameters:
    • Hostname: Specifies the server where the MySQL database is hosted. Typically, it's "localhost" if the database is on the same server as the PHP code.
    • Username: The username used to authenticate with the MySQL server.
    • Password: The password associated with the username for authentication.
  • "localhost:3306" is the default host and port for MySQL databases. The port 3306 is where MySQL usually listens for connections.
  • We are using the mysqli method to establish the database connection. MySQLi is a PHP extension used for interacting with MySQL databases, offering both procedural and object-oriented approaches.

Explanation of Code:

                    
<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "";

// Create a connection to the MySQL database
$conn = mysqli_connect($servername, $username, $password);

// Check if the connection was successful
if (!$conn) {
    // If connection fails, terminate the script and display an error message
    die("Connection failed: " . mysqli_connect_error());
} else {
    // If the connection is successful, display a success message
echo "Connected successfully";
}
mysqli_close($conn);
?>
                
            

In the code:

  • $servername, $username, and $password are variables holding the database credentials.
  • mysqli_connect() is used to create a connection to the MySQL database.
  • The if (!$conn) statement checks if the connection was successful. If not, die() terminates the script and displays the error message retrieved from mysqli_connect_error().
  • If the connection is successful, the script continues and displays "Connected successfully".
  • The mysqli_close() function is used to close a previously opened database connection. This function takes a single parameter, which is the connection object that was created by the mysqli_connect() function.

PHP MySQL Database Connectivity

PHP allows you to connect to a MySQL database using the mysqli_connect() function.

Steps to Connect to MySQL Database in PHP

  1. Set Database Credentials: Define variables for hostname, username, password, and database name.
  2. Establish Connection: Use mysqli_connect() function to establish a connection to the MySQL database.
  3. Check Connection: Verify if the connection was successful using an if statement.
  4. Perform Database Operations: Once connected, you can execute SQL queries to perform various database operations.
  5. Close Connection: After completing the database operations, close the connection using mysqli_close() function to free up resources.

PHP MySQL Database Connectivity Example

Example:

                    
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = 'your_password';
$dbname = 'your_database';

// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
    die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';

// Perform database operations here

// Closing the connection
mysqli_close($conn);
?>
                
            

PHP MySQL Create Database

Since PHP 4.3, the mysql_create_db() function is deprecated. Now it is recommended to use one of the two alternatives:

  • mysqli_query()
  • PDO::__query()

PHP MySQLi Create Database Example

                    
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';

$conn = mysqli_connect($host, $user, $pass);

if(!$conn) {
    die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully';

$sql = 'CREATE DATABASE mydb';

if(mysqli_query($conn, $sql)) {
    echo "Database mydb created successfully.";
} else {
    echo "Sorry, database creation failed: " . mysqli_error($conn);
}

mysqli_close($conn);
?>
                
            

Explanation of the Code

  • Connection to Database:
                                
    $conn = mysqli_connect($host, $user, $pass);
                                
                            
    This line establishes a connection to the MySQL server using the specified hostname, username, and password.
  • Check Connection:
                                
    if(!$conn) { die('Could not connect: ' . ysqli_connect_error()); }
                                
                            
    This block checks if the connection was successful. If not, it outputs an error message and terminates the script.
  • Create Database:
                                
    $sql = 'CREATE DATABASE mydb';
                                
                            
    This line stores the SQL query for creating a new database named 'mydb'.
  • Execute Query:
                                
    if(mysqli_query($conn, $sql)) { 
        echo "Database mydb created successfully."; 
    } else { 
        echo "Sorry, database creation failed: " . mysqli_error($conn); 
    }
                                
                            
    This block executes the SQL query. It checks the success of the query and outputs an appropriate message.
  • Close Connection:
                                
    mysqli_close($conn);
                                
                            
    This line closes the database connection that was previously opened.

PHP MySQL Create Table

PHP mysqli_query() function is used to create tables in MySQL databases.

PHP MySQLi Create Table Example

Example:

                    
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';

// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
    die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';

// SQL query to create a table
$sql = "CREATE TABLE emp5 (
    id INT AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    emp_salary INT NOT NULL,
    PRIMARY KEY (id)
)";

if (mysqli_query($conn, $sql)) {
    echo "Table emp5 created successfully";
} else {
    echo "Could not create table: " . mysqli_error($conn);
}

// Closing the connection
mysqli_close($conn);
?>
                
            

Explanation of the Code

  1. Connecting to the Database:
                                
    $host = 'localhost:3306';
    $user = 'root';
    $pass = '';
    $dbname = 'test';
    $conn = mysqli_connect($host, $user, $pass, $dbname);
                            
                        
    • $host: The hostname and port number where the MySQL server is running.
    • $user: The MySQL username.
    • $pass: The MySQL password.
    • $dbname: The name of the database to connect to.
    • mysqli_connect(): Establishes a connection to the MySQL server.
  2. Creating the Table:
                                
    $sql = "CREATE TABLE emp5 (
        id INT AUTO_INCREMENT,
        name VARCHAR(20) NOT NULL,
        emp_salary INT NOT NULL,
        PRIMARY KEY (id)
    )";
                            
                        
    • AUTO_INCREMENT: Automatically increments the value of id for each new record.
    • VARCHAR(20) NOT NULL: Defines a column name that can store a string of up to 20 characters and cannot be null.
    • INT NOT NULL: Defines a column emp_salary that stores an integer and cannot be null.
    • PRIMARY KEY (id): Sets the id column as the primary key of the table.
  3. Executing the Query:
                                
    if (mysqli_query($conn, $sql)) {
        echo "Table emp5 created successfully";
    } else {
        echo "Could not create table: " . mysqli_error($conn);
    }
                            
                        
    • mysqli_query(): Executes the SQL query against the MySQL database.
    • mysqli_error(): Returns the error description of the last MySQL operation.

PHP MySQL Insert Record

                    
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';

// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
    die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';

// SQL query to insert a record
$sql = "INSERT INTO emp4 (name, salary) VALUES ('sonoo', 9000)";

if (mysqli_query($conn, $sql)) {
    echo "Record inserted successfully";
} else {
    echo "Could not insert record: " . mysqli_error($conn);
}

// Closing the connection
mysqli_close($conn);
?>
    

Explanation of the Code

  1. Inserting a Record:
                                
    $sql = "INSERT INTO emp4 (name, salary) VALUES ('sonoo', 9000)";
    
    if (mysqli_query($conn, $sql)) {
        echo "Record inserted successfully";
    } else {
        echo "Could not insert record: " . mysqli_error($conn);
    }
                                
                            
    • INSERT INTO emp4 (name, salary) VALUES ('sonoo', 9000): SQL query to insert a record into the emp4 table with specified values.
    • mysqli_query(): Executes the SQL query against the MySQL database.

PHP MySQL Update Record

                
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';

// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
    die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';

// Variables to update the record
$id = 2;
$name = "Rahul";
$salary = 80000;

// SQL query to update a record
$sql = "UPDATE emp4 SET name='$name', salary=$salary WHERE id=$id";

if (mysqli_query($conn, $sql)) {
    echo "Record updated successfully";
} else {
    echo "Could not update record: " . mysqli_error($conn);
}

// Closing the connection
mysqli_close($conn);
?>
                
            

PHP MySQL Delete Record

    
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';

// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
    die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';

// SQL query to delete a record
$id = 2;
$sql = "DELETE FROM emp4 WHERE id=$id";

if (mysqli_query($conn, $sql)) {
    echo "Record deleted successfully";
} else {
    echo "Could not delete record: " . mysqli_error($conn);
}

// Closing the connection
mysqli_close($conn);
?>
                    
                
                        
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';

// Establishing the connection
$conn = mysqli_connect($host, $user, $pass);

if (!$conn) {
    die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';

// Creating a database
$sql = "CREATE DATABASE IF NOT EXISTS $dbname";
if (mysqli_query($conn, $sql)) {
    echo "Database $dbname created successfully<br/>";
} else {
    echo "Could not create database: " . mysqli_error($conn) . "<br/>";
}

// Selecting the database
mysqli_select_db($conn, $dbname);

// Creating a table
$sql = "CREATE TABLE IF NOT EXISTS emp4 (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(20) NOT NULL,
    salary INT NOT NULL
)";
if (mysqli_query($conn, $sql)) {
    echo "Table emp4 created successfully<br/>";
} else {
    echo "Could not create table: " . mysqli_error($conn) . "<br/>";
}

// Inserting a record
$sql = "INSERT INTO emp4 (name, salary) VALUES ('sonoo', 9000)";
if (mysqli_query($conn, $sql)) {
    echo "Record inserted successfully<br/>";
} else {
    echo "Could not insert record: " . mysqli_error($conn) . "<br/>";
}

// Updating a record
$id = 1;
$name = "Rahul";
$salary = 80000;
$sql = "UPDATE emp4 SET name='$name', salary=$salary WHERE id=$id";
if (mysqli_query($conn, $sql)) {
    echo "Record updated successfully<br/>";
} else {
    echo "Could not update record: " . mysqli_error($conn) . "<br/>";
}

// Deleting a record
$id = 1;
$sql = "DELETE FROM emp4 WHERE id=$id";
if (mysqli_query($conn, $sql)) {
    echo "Record deleted successfully<br/>";
} else {
    echo "Could not delete record: " . mysqli_error($conn) . "<br/>";
}

// Closing the connection
mysqli_close($conn);
?>
                        
                    

Create a User Registration Page with the Help of PHP and MySQL

  • We can create everything in one PHP file, but we are creating it in two separate files: an HTML file to display the form, and a PHP file to handle the form submission.
                        
<!DOCTYPE html>
<html>
<head>
    <title>User Registration</title>
</head>
<body>
    <h2>User Registration</h2>
    <form action="register.php" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required><br><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br><br>

        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required><br><br>

        <input type="submit" value="Register">
    </form>
</body>
</html>
                        
                    
                            
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'user_registration';

// Establishing the connection
$conn = mysqli_connect($host, $user, $pass);

if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';

// Creating a database
$sql = "CREATE DATABASE IF NOT EXISTS $dbname";
if (mysqli_query($conn, $sql)) {
echo "Database $dbname created successfully<br/>";
} else {
echo "Could not create database: " . mysqli_error($conn) . "<br/>";
}

// Selecting the database
mysqli_select_db($conn, $dbname);

// Creating a table
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table users created successfully<br/>";
} else {
echo "Could not create table: " . mysqli_error($conn) . "<br/>";
}

// Getting form data
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];

// Inserting a record
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
if (mysqli_query($conn, $sql)) {
echo "Registration successful!<br/>";
} else {
echo "Could not register user: " . mysqli_error($conn) . "<br/>";
}

// Closing the connection
mysqli_close($conn);
?>
                            
                        
  • If the registration database is already created in MySQL, there is no need to create it in the PHP file.

Reference