Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PHP: A Basic Introduction

In the digital age, websites are like virtual homes for information and services. Have you ever wondered how these websites work, how they’re built, and how they interact with users? Well, that’s where PHP comes into play. PHP, which stands for Hypertext Preprocessor, is a special kind of computer language that helps developers create dynamic and interactive websites. In this article, we’ll delve into the basics of PHP in simple words along with Code examples to give you a better understanding of this fascinating web development tool.

What is PHP?

Imagine you’re baking a cake. You have different ingredients like flour, sugar, eggs, and chocolate. To make a cake, you need to mix these ingredients in the right way and bake them. Similarly, when you want to create a website, you have different elements like text, images, buttons, and forms. PHP is like the secret recipe that combines these elements together and makes your website come to life.

Originally standing for “Personal Home Page”, PHP is a general purpose language, developed in 1993 and released in 1995 Danish-Canadian programmer Rasmus Lerdorf, with focus on web development. As of 2023, according to W3Tech’s report, 77.8% of all websites use it in their servers(This one included!).

How Does PHP Work?

PHP is a scripting language that works behind the scenes on a Web Server. When a user visits a webpage, the web server receives the request. If the page contains Php Code, the server doesn’t send the PHP code directly to the user’s browser. Instead, it processes the PHP code first.

Here’s how it works:

  1. User Request: A user clicks on a link or enters a web address in their browser.
  2. Web Server: The web server receives the request for a specific webpage.
  3. PHP Processor: If the webpage has PHP code, the web server sends the PHP code to a special program called the PHP processor.
  4. Code Execution: The PHP processor reads and executes the PHP code. It can do things like gather data from a database, perform calculations, and create dynamic content.
  5. Result: After the PHP code is executed, the processor generates regular HTML content (the stuff browsers understand) mixed with the dynamic data from the PHP code.
  6. Browser Display: The web server sends the resulting HTML content back to the user’s browser.
  7. User Sees: The user’s browser receives the HTML content, which is then displayed as a fully-formed webpage with dynamic elements and information.

All PHP code, run using PHP 7 and above, is JIT compiled. This means that the PHP processor will simply interpret the code(which is slow but uses less memory) until either it finds a part of it that is slow or repeated many times. Then it will grab that part, optimize and compile to machine code, allowing it to run much faster.

The Power of Variables

In PHP, variables are like containers that hold different kinds of information. Think of them as boxes that you can label with names. For example, you could have a variable named $username that holds the name of a user who just logged in. You can use these variables to remember and work with information as your website goes along.

Here’s a code example of using variables in PHP:

All variables must start with $. They’re also weakly typed by default(without need for type declaration). Example:

$dynamicVar = 5; // It's a int
$dynamicVar = "changed"; // Now it's a string
$dynamicVar = 3.14; // And now it's a floating-point number

In more recent versions of PHP, things like functions can restrain what kind of argument types they’ll receive, like this:

function test(string $name, bool $is_admin) {//can only receive one string and one bool for arguments
    //do something
}

Mixing PHP with HTML

HTML is the skeleton of a web page, and other than CSS and javascript, its the only thing the browser understands. It gives structure to your page, like where text and images go. But what if you want to add some fancy stuff that changes based on what the user does? This is where PHP comes in.

Imagine you have a weather website. You want to show the current temperature. With just HTML, the temperature would be stuck and wouldn’t change. But if you use PHP, you can fetch the latest temperature from a weather service and display it on your website. This makes your website feel alive and up-to-date.

Here’s a code example of mixing PHP with HTML to display the current temperature:




    Weather Website

Welcome to Weather Website

Current temperature: °C

Making Decisions with PHP

Websites often need to make decisions based on what users do. For instance, if you’re building a quiz website and someone scores 80 points, you might want to tell them, “Great job!” If they score lower, you could say, “Keep practicing!” PHP helps your website make these decisions. It checks things and then decides what to show to the user.

Here’s a code example of making decisions with PHP:

= 80) {
    echo "Great job! You passed the quiz.";
} else {
    echo "Keep practicing. You can do better!";}
?>

Loops for Repetitive Tasks

Imagine you’re writing a big list of your favorite foods on your website. Typing each one out would take a long time. But with PHP, you can use something called a “loop” to do this more easily. A loop is like a magic trick that repeats an action. So, you write the code for listing one food, and PHP repeats it for all the foods in your list.

Here’s a code example of using a foreach loop in PHP:

";

foreach ($favoriteFoods as $food) {
    echo "- " . $food . "
"; } ?>

PHP and MySQL

PHP and MySQL have evolved to work really well with one another over the years. I won’t go over what is and how MySQL works in this article, as I’ve another one that covers the entire basics of it here, but I’ll talk about how to connect one to the other.

The most common way to communicate between the two, is having them both running and using PDO(PHP Data Objects, a library that usually comes with PHP), to make the bridge. Within your PHP script, start by creating a new PDO object using the appropriate database credentials and settings. Use a try-catch block to handle connection errors. Next, you can prepare and execute SQL queries using prepared statements(To avoid SQL Injection attacks). Finally, close the connection when done to free up resources.

Here’s some example code:

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Example SQL query
    $sql = "SELECT * FROM users WHERE id = :id";

    // Prepare the statement, to clean it from SQL Injections
    $stmt = $pdo->prepare($sql);

    // Bind parameters and execute
    $id = 1;
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();

    // Fetch the results
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    // Print the results
    print_r($result);
    
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

// Close the connection
$pdo = null;
?>

Wrapping Up

PHP is like a wizard for web development. It makes your websites more interactive and useful by processing data, making decisions, and showing things that change. It’s a tool that helps you create web pages that aren’t just pretty pictures but also functional and engaging spaces where people can do things. As you dive deeper into the world of web development, understanding PHP will empower you to create amazing online experiences.


Get articles on your E-mail



This post first appeared on Peq42 - Indie Game Dev, please read the originial post: here

Share the post

PHP: A Basic Introduction

×

Subscribe to Peq42 - Indie Game Dev

Get updates delivered right to your inbox!

Thank you for your subscription

×