Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Deploying a PHP, Apache, and MySQL Stack: Setup and Fundamental Concepts

Tech 1

Web pages are categorized as static or dynamic. To understand these, we must first differentiate between servers and clients. A server is a device running server software that provides services like web browsing and database queries to clients. Conversely, a client, using software such as a browser, accesses these services. In essence, the server provides services, and the client consumes them.

Static Web Pages

Static web pages form the foundation of websites. They are standard HTML files, typically with extensions .htm or .html, containing text, images, sounds, Flash animations, client-side scripts, and ActiveX controls.

Static pages are defined as those without a backend database, containing no programs, and being non-interactive. They are relatively difficult to update, making them suitable for websites requiring infrequent changes.

A common misconception is that static pages cannot include motion; they can feature animations like GIFs, Flash, or scrolling text.

To serve a static page, a client sends a request via its browser. The server accepts the request, locates the corresponding pre-edited page file, and returns it to the client. The page content is not generated automatically.

Characteristics of static web pages include:

  • Pages do not update automatically; modifying content requires editing the HTML source file and re-uploading it, leading to significant maintenance overhead.
  • Content remains constant regardless of who views it, when, or from where (excluding minor effects from JavaScript).
  • Once published, a static page exists as a real file on the server with a unique URL.
  • Implementing interactive features with static pages is highly limited and challenging due to the lack of dynamic content generation.

Dynamic Web Pages

Dynamic web pages integrate basic HTML syntax with server-side programming languages like PHP, Java, or Python, and database technology. This enables efficient, dynamic, and interactive management of website content and style. Essentially, any webpage generated using technologies that combine programming languages and databases is dynamic.

While the underlying page code might not change, the displayed content can vary based on time, enviroment, or the outcome of data base operations.

Note: Dynamic web pages are unrelated to visual animations or effects. A dynamic page can be text-only or contain animations. The key distinction is the use of server-side technologies (PHP, JSP, etc.) to generate the page.

Compared to static pages, dynamic pages have these characteristics:

  • They execute on the server. The client only sees the output, not the source code. Static pages are delivered unchanged from the server file.
  • Content can differ based on who views it, when, and where, depending on code execution results.
  • A dynamic page is not a standalone file on the server; it's assembled and returned as a complete page only when requested by a client.
  • They facilitate easier human-computer interaction and enable more powerful functionalities by connecting to databases.
  • Maintaining a website built with dynamic pages is simpler, often requiring only updates to the underlying data (e.g., in a database).

The serving process differs: the client sends a request, the server processes the dynamic page's internal code, and then sends the generated result to the client.

Key Differences: Dynamic vs. Static Pages

  1. Updates and Maintenance: Static page content resides on the server file system. Any change necessitates editing the source file and re-uploading. Without database support, maintenance becomes difficult for large sites. Dynamic pages generate content on-the-fly based on requests and typically use databases, drastically reducing maintenance workload.
  2. Interactivity: Static pages offer limited functionality due to fixed content, resulting in poor interactivity. Dynamic pages support complex features like user login, registration, and data queries.
  3. Response Speed: Static pages, with fixed content and no database queries, are easily indexed by search engines and generally load faster. Dynamic pages involve server-side processing and database access, which can slow response times.

Setting Up a PHP Development Environment

For beginners on Windows, using XAMPP is recommended for an easy installation of the integrated Apache, PHP, and MySQL environment. Download the PHP 7 version from the official Apache Friends website.

After downloading the EXE file, run the installer. Post-installation, navigate to the installation directory and run manager-windows.exe. In the management window, check the status of MySQL and Apache in the "Manage Servers" tab.

By default, application files reside in the apache2/htdocs subdirectory. Create a file named test.php in this directory with the following content:

<?php
phpinfo();

Access http://localhost/test.php in a browser. If a page displaying PHP configuration informasion appears, the installation is successful.

Writing Your First PHP Script

To output "Hello World!" in a browser, create a simple PHP file:

<?php
echo "Hello World!";

The <?php and ?> tags denote the start and end of PHP code (the closing ?> is optional). The echo statement outputs the string. A semicolon ; terminates the statement.

PHP source files use the .php extension. Place them in your server's web root directory:

  • XAMPP: htdocs folder.
  • PHPStudy: WWW folder.

Common practice is to name the main file index.php. Ensure the Apache service in XAMPP is running, then access http://localhost in your browser to see the output.

Introduction to MySQL Database

PHP applications often require persistent data storage. While XML or text files are options, databases like MySQL provide superior management for substantial data.

MySQL is a secure, cross-platform, high-performance database system that integrates well with PHP. It's open-source, fast, and has a low total cost of ownership, making it popular for small to medium web applications.

Key features of MySQL include:

  1. Powerful storage engines optimized for different use cases.
  2. Cross-platform support (Linux, Windows, etc.).
  3. High-speed performance via optimized algorithms and structures.
  4. Support for object-oriented programming in connecting languages.
  5. Robust security with encrypted password transmission.
  6. Free to use under the GPL license.
  7. APIs for numerous programming languages including PHP, Java, and Python.
  8. Large storage capacity, limited primarily by the operating system.
  9. Extensive built-in functions and libraries for web development.

In web development, dynamic sites frequently store content (like news articles) in a database. Upon user request, a PHP script fetches the specific data via a query and formats it into HTML for display. Conversely, data submitted via forms can be inserted into the database through PHP.

Common web stacks are LAMP (Linux, Apache, MySQL, PHP/Python/Perl) and LNMP (using Nginx). PHP interacts with MySQL via extensions like MySQLi, executing queries to store, retrieve, and manage data.

Connecting PHP to MySQL

Using PHP to operate a MySQL database involves several steps: connecting, executing queries, processing results, and closing the connection. Ensure the MySQLi extension is enabled in your php.ini file (e.g., uncomment extension=mysqli). Verify it's active by checking the output of phpinfo();.

Establishing a Connection

The mysqli_connect() function (or the mysqli constructor in object-oriented style) creates a connection.

Procedural Example:

<?php
$dbHost = '127.0.0.1';
$dbUser = 'app_user';
$dbPass = 'secure_pass';
$dbName = 'application_db';

$dbLink = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if (!$dbLink) {
    exit('Connection failed: ' . mysqli_connect_error());
}
mysqli_set_charset($dbLink, 'utf8mb4');

// ... perform database operations ...

mysqli_close($dbLink);
?>

Object-Oriented Example:

<?php
$dbHost = 'localhost';
$dbUser = 'app_user';
$dbPass = 'secure_pass';
$dbName = 'application_db';

try {
    $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
    if ($mysqli->connect_errno) {
        throw new Exception('Connection error: ' . $mysqli->connect_error);
    }
    $mysqli->set_charset('utf8mb4');
    // ... perform operations using $mysqli object ...
    $mysqli->close();
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Selecting a Database

If the database name isn't specified during connection, use mysqli_select_db().

Procedural: mysqli_select_db($link, 'database_name'); Object-Oriented: $mysqli->select_db('database_name');

For maintainability, place connection code in a separate file and include it where needed using require or include.

Executing SQL Queries

Use mysqli_query() to run SQL statements like SELECT, INSERT, UPDATE, DELETE.

Example (Object-Oriented):

$sql = "SELECT id, username, email FROM users WHERE active = 1";
$resultSet = $mysqli->query($sql);
if ($resultSet) {
    // Process results
    $mysqli->close();
} else {
    echo 'Query error: ' . $mysqli->error;
}

Example (Procedural):

$sql = "SELECT id, username, email FROM users WHERE active = 1";
$result = mysqli_query($dbLink, $sql);
if ($result) {
    // Process results
    mysqli_close($dbLink);
} else {
    echo 'Query failed: ' . mysqli_error($dbLink);
}

Fetching Query Results

After a successful SELECT query, various functions retrieve data from the result set.

  1. mysqli_fetch_row(): Returns a row as a numeric array.
    while ($row = mysqli_fetch_row($result)) {
        print_r($row); // Outputs: Array ( [0] => 101 [1] => john_doe [2] => john@example.com )
    }
    
  2. mysqli_fetch_assoc(): Returns a row as an associative array.
    while ($row = $resultSet->fetch_assoc()) {
        echo $row['username'] . ': ' . $row['email'] . "\n";
    }
    
  3. mysqli_fetch_array(): Can return an associative array, a numeric array, or both (default). Specify type: MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.
    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
    
  4. mysqli_fetch_all(): Fetches all result rows at once into an array.
    $allRows = $resultSet->fetch_all(MYSQLI_ASSOC);
    foreach ($allRows as $user) {
        // Process each user array
    }
    
  5. mysqli_fetch_object(): Returns a row as an object with column names as properties.
    while ($obj = mysqli_fetch_object($result)) {
        echo $obj->username . '\n';
    }
    
Tags: PHP

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.