PHP Tutorials for Beginners

Form Handling Example

This example demonstrates how to handle form data using PHP. It includes both the HTML form and the PHP script to process the input.

HTML Form

                
<form action="php-examples.php" method="post">
    Name: <input type="text" name="name"><br>
    Email: <input type="email" name="email"><br>
    <input type="submit" value="Submit">
</form>
                
            

PHP Script

                
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);
    echo "Name: " . $name . "<br>";
    echo "Email: " . $email;
}
?>
                
            

Database Connection Example

This example shows how to connect to a MySQL database using PHP’s PDO extension.

                
<?php
$dsn = "mysql:host=localhost;dbname=testdb";
$username = "root";
$password = "";

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>
                
            

File Upload Example

This example demonstrates how to upload files using PHP. It includes the HTML form for file upload and the PHP script to handle the uploaded file.

HTML Form

                
<form action="php-examples.php" method="post" enctype="multipart/form-data">
    Select file: <input type="file" name="fileToUpload"><br>
    <input type="submit" value="Upload File">
</form>
                
            

PHP Script

                
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES['fileToUpload'])) {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
                
            

Further Reading

For more examples and in-depth tutorials, check out the following resources: