Easy Steps to write a PHP code in Different ways

Open a text editor, such as VSCode, Notepad.
Write your PHP code.
Save the file with a .php extension (e.g., example.php).
Save the File in XAMPP Directory:

After writing your code, save it in the XAMPP htdocs folder.
If XAMPP is installed on your C: drive, the file path should be C:/xampp/htdocs.
Run PHP Code in Browser:

Open the XAMPP Control Panel.
Start the Apache and MySQL servers.
In a web browser, type localhost/filename.php to run the PHP file.
If your file is in a subfolder within htdocs, use localhost/subfolder_name/filename.php.
Three Ways to Write PHP Code:
Without HTML Markup:

You can write PHP code without any HTML tags when there is no need for a user interface.

<?php 
    $a = 20; 
    $b = 10; 
    $c = $a + $b; 
    echo "The addition of a and b is " . $c; 
?>

Output:
The addition of a and b is 30

Embedding HTML in PHP Code:

PHP code can include HTML tags, allowing you to generate HTML content dynamically.

<?php 
    echo "<html>"; 
    echo "<h1>Welcome</h1>"; 
    echo "</html>"; 
?>

//output Welcome

Embedding PHP in HTML:

You can insert PHP code inside HTML for dynamic content on web pages.

<html>  
<body>  
<?php  
    echo "Your first PHP code";  
?>  
</body>  
</html>

//output Your first PHP code

Choosing the Best Approach:
All three methods are effective, and the choice depends on your project:

HTML-Only Front-End: If you only need to create static front-end pages, HTML alone is sufficient.
Dynamic Pages with Database: For dynamic pages interacting with a database, use PHP embedded in HTML.
Regardless of the method, always save your files with the .php extension to ensure that your code interacts with the server and database.

Important Tip:
XAMPP is required to run PHP programs locally. Ensure you save all PHP files in the htdocs folder and follow the steps mentioned above to view them in a browser.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *