Back

PHP Tutorial: Basics 1


PHP Tutorial: Basics 1

Welcome to this PHP tutorial! In this guide, we will create a dynamic form for inserting and updating data in a MySQL database. The form will feature dropdowns for selecting provinces and cities in Indonesia. We will use PHP and JavaScript to dynamically populate the city dropdown based on the selected province.

Prerequisites

Before you begin, make sure you have the following:

  • A basic understanding of HTML, CSS, and PHP.
  • A local server environment (e.g., XAMPP, WAMP, or MAMP) to run your PHP code.
  • MySQL database installed.

For additional learning, you can refer to W3Schools PHP Tutorial.

Step 1: Create the Database

First, create a database and table in MySQL.

Open your MySQL command-line client or any MySQL GUI tool and run the following commands:

CREATE DATABASE tes1;

USE tes1;

CREATE TABLE ekonomi (
    id INT AUTO_INCREMENT PRIMARY KEY,
    prov VARCHAR(255) NOT NULL,
    kab_kot VARCHAR(255) NOT NULL,
    eko FLOAT NOT NULL
);

Explanation

  • CREATE DATABASE tes1;: This command creates a new database named tes1.
  • USE tes1;: This command selects the tes1 database for subsequent operations.
  • CREATE TABLE ekonomi (...);: This command creates a new table named ekonomi with columns id, prov, kab_kot, and eko. The id column is an auto-incrementing primary key.

Step 2: Set Up the HTML and CSS

Create a file named insert.php and set up the HTML structure with CSS for styling.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="icon" href="https://upload.wikimedia.org/wikipedia/commons/d/de/Lambang_Kota_Cilegon.png">
    <title>Insert New Data</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 50%;
            margin: auto;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-top: 50px;
            border-radius: 8px;
            text-align: center;
        }
        h1 {
            text-align: center;
        }
        label {
            display: block;
            margin-top: 10px;
        }
        select, input[type="number"] {
            width: 100%;
            padding: 10px;
            margin-top: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        input[type="submit"] {
            width: 100%;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            margin-top: 20px;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #45a049;
        }
        .logo {
            display: block;
            margin: 0 auto 20px auto;
        }
    </style>
</head>
<body>

<div class="container">
    <img src="https://upload.wikimedia.org/wikipedia/commons/d/de/Lambang_Kota_Cilegon.png" alt="Logo" class="logo" width="100">
    <h1>Insert New Data</h1>
    <form action="insert_action.php" method="post">
        <label for="prov">Provinsi:</label>
        <select id="prov" name="prov" required onchange="populateCities()">
            <option value="">Select Province</option>
            <?php
            $provinces = [
                "Aceh", "Bali", "Banten", "Bengkulu", "Gorontalo", "Jakarta", "Jambi", "West Java", "Central Java", "East Java",
                "West Kalimantan", "South Kalimantan", "Central Kalimantan", "East Kalimantan", "North Kalimantan",
                "Bangka Belitung", "Lampung", "Riau", "Riau Islands", "West Sumatra", "South Sumatra", "North Sumatra",
                "West Nusa Tenggara", "East Nusa Tenggara", "Papua", "West Papua", "Southeast Sulawesi", "Central Sulawesi",
                "South Sulawesi", "West Sulawesi", "North Sulawesi", "Yogyakarta"
            ];
            foreach ($provinces as $province) {
                echo "<option value=\"$province\">$province</option>";
            }
            ?>
        </select>

        <label for="kab_kot">Kabupaten:</label>
        <select id="kab_kot" name="kab_kot" required>
            <option value="">Select City</option>
        </select>

        <label for="eko">Ekonomi:</label>
        <input type="number" id="eko" name="eko" required>

        <input type="submit" value="Insert">
    </form>
</div>

<script>
    const citiesByProvince = {
        "Aceh": ["Banda Aceh", "Langsa", "Lhokseumawe", "Sabang", "Subulussalam"],
        "Bali": ["Denpasar"],
        "Banten": ["Cilegon", "Serang", "South Tangerang", "Tangerang"],
        "Bengkulu": ["Bengkulu"],
        "Gorontalo": ["Gorontalo"],
        "Jakarta": ["Central Jakarta", "East Jakarta", "North Jakarta", "South Jakarta", "West Jakarta"],
        "Jambi": ["Jambi"],
        "West Java": ["Bandung", "Bekasi", "Bogor", "Cimahi", "Cirebon", "Depok", "Sukabumi", "Tasikmalaya"],
        "Central Java": ["Magelang", "Pekalongan", "Salatiga", "Semarang", "Surakarta", "Tegal"],
        "East Java": ["Batu", "Blitar", "Kediri", "Madiun", "Malang", "Mojokerto", "Pasuruan", "Probolinggo", "Surabaya"],
        "West Kalimantan": ["Pontianak", "Singkawang"],
        "South Kalimantan": ["Banjarbaru", "Banjarmasin"],
        "Central Kalimantan": ["Palangka Raya"],
        "East Kalimantan": ["Balikpapan", "Bontang", "Samarinda"],
        "North Kalimantan": ["Tarakan"],
        "Bangka Belitung": ["Pangkal Pinang"],
        "Lampung": ["Bandar Lampung", "Metro"],
        "Riau": ["Dumai", "Pekanbaru"],
        "Riau Islands": ["Batam", "Tanjung Pinang"],
        "West Sumatra": ["Bukittinggi", "Padang", "Padang Panjang", "Pariaman", "Payakumbuh", "Sawahlunto", "Solok"],
        "South Sumatra": ["Lubuklinggau", "Pagar Alam", "Palembang", "Prabumulih"],
        "North Sumatra": ["Binjai", "Medan", "Padang Sidempuan", "Pematangsiantar", "Sibolga", "Tanjungbalai", "Tebing Tinggi"],
        "West Nusa Tenggara": ["Bima", "Mataram"],
        "East Nusa Tenggara": ["Kupang"],
        "Papua": ["Jayapura"],
        "West Papua": ["Sorong"],
        "Southeast Sulawesi": ["Bau-Bau", "Kendari"],
        "Central Sulawesi": ["Palu"],
        "South Sulawesi": ["Makassar", "Palopo", "Parepare"],
        "West Sulawesi": ["Mamuju"],
        "North Sulawesi": ["Bitung", "Kotamobagu", "Manado", "Tomohon"],
        "Yogyakarta": ["Yogyakarta"]
    };

    function populateCities() {
        const provinceSelect = document.getElementById('prov');
        const citySelect = document.getElementById('kab_kot');
        const selectedProvince = provinceSelect.value;

        // Clear the city dropdown
        citySelect.innerHTML = '<option value="">Select City</option>';

        if (selectedProvince in citiesByProvince) {
            const cities = citiesByProvince[selectedProvince];
            cities.forEach(city => {
                const option = document.createElement('option');
                option.value = city;
                option.text = city;
                citySelect.appendChild(option);
            });
        }
    }
</script>

</body>
</html>

Explanation

  1. HTML Structure: This defines the structure of the form. The <head> section includes the meta tags, favicon, title, and CSS styles. The <body> section includes the form

and the JavaScript code. 2. CSS Styles:

  • .container: Centers the form and applies styles such as padding, background color, box shadow, and border radius.
  • h1: Centers the heading.
  • label, select, input[type="number"]: Styles the form elements.
  • input[type="submit"]: Styles the submit button and adds a hover effect.
  • .logo: Styles the logo image to center it and add spacing.
  1. PHP Code:
    • <?php ... ?>: Embeds PHP code within the HTML.
    • $provinces: An array containing the list of provinces.
    • foreach ($provinces as $province) { ... }: Loops through the provinces array and creates an <option> element for each province.
  2. JavaScript Code:
    • citiesByProvince: An object mapping each province to its list of cities.
    • populateCities(): A function that populates the city dropdown based on the selected province. It is called whenever the province dropdown changes (onchange="populateCities()").

Step 3: Handle Form Submission

Create a file named insert_action.php to handle the form submission and insert data into the database.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tes1";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$prov = $_POST['prov'];
$kab_kot = $_POST['kab_kot'];
$eko = $_POST['eko'];

$sql = "INSERT INTO ekonomi (prov, kab_kot, eko) VALUES ('$prov', '$kab_kot', '$eko')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

header("Location: insert.php");
exit();
?>

Explanation

  1. Database Connection: Connects to the MySQL database using the credentials provided.
  2. Form Data: Retrieves the form data using the $_POST superglobal.
  3. SQL Query: Constructs an SQL INSERT query to add the form data to the ekonomi table.
  4. Error Handling: Checks if the query was successful and displays an appropriate message.
  5. Redirection: Redirects back to the insert.php form after submission.

Step 4: Create the Update Form

Create a file named update.php to display the update form with pre-filled data from the database.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="icon" href="https://upload.wikimedia.org/wikipedia/commons/d/de/Lambang_Kota_Cilegon.png">
    <title>Update Data</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 50%;
            margin: auto;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-top: 50px;
            border-radius: 8px;
            text-align: center;
        }
        h1 {
            text-align: center;
        }
        label {
            display: block;
            margin-top: 10px;
        }
        select, input[type="number"] {
            width: 100%;
            padding: 10px;
            margin-top: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        input[type="submit"] {
            width: 100%;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            margin-top: 20px;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #45a049;
        }
        .logo {
            display: block;
            margin: 0 auto 20px auto;
        }
    </style>
</head>
<body>

<div class="container">
    <img src="https://upload.wikimedia.org/wikipedia/commons/d/de/Lambang_Kota_Cilegon.png" alt="Logo" class="logo" width="100">
    <h1>Update Data</h1>
    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "tes1";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }

    $id = $_GET['id'];

    $sql = "SELECT * FROM ekonomi WHERE id=$id";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
      $row = $result->fetch_assoc();
    ?>

    <form action="update_action.php" method="post">
        <input type="hidden" name="id" value="<?php echo $row['id']; ?>">

        <label for="prov">Provinsi:</label>
        <select id="prov" name="prov" required onchange="populateCities()">
            <?php
            foreach ($provinces as $province) {
                $selected = $province == $row['prov'] ? 'selected' : '';
                echo "<option value=\"$province\" $selected>$province</option>";
            }
            ?>
        </select>

        <label for="kab_kot">Kabupaten:</label>
        <select id="kab_kot" name="kab_kot" required>
            <option value="">Select City</option>
        </select>

        <label for="eko">Ekonomi:</label>
        <input type="number" id="eko" name="eko" value="<?php echo $row['eko']; ?>" required>

        <input type="submit" value="Update">
    </form>

    <?php
    } else {
      echo "<p>No record found</p>";
    }

    $conn->close();
    ?>
</div>

<script>
    document.getElementById('prov').addEventListener('change', populateCities);
    window.addEventListener('load', populateCities);

    function populateCities() {
        const provinceSelect = document.getElementById('prov');
        const citySelect = document.getElementById('kab_kot');
        const selectedProvince = provinceSelect.value;
        const currentCity = "<?php echo $row['kab_kot']; ?>";

        // Clear the city dropdown
        citySelect.innerHTML = '<option value="">Select City</option>';

        if (selectedProvince in citiesByProvince) {
            const cities = citiesByProvince[selectedProvince];
            cities.forEach(city => {
                const option = document.createElement('option');
                option.value = city;
                option.text = city;
                if (city === currentCity) {
                    option.selected = true;
                }
                citySelect.appendChild(option);
            });
        }
    }
</script>

</body>
</html>

Explanation

  1. HTML and CSS: The structure and styles are similar to insert.php.
  2. PHP Code:
    • Connects to the database and retrieves the record with the specified ID ($_GET['id']).
    • Pre-fills the form with the existing data from the database.
  3. JavaScript Code:
    • populateCities(): Populates the city dropdown based on the selected province and pre-selects the current city.

Step 5: Handle Update Form Submission

Create a file named update_action.php to handle the form submission and update the data in the database.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tes1";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$id = $_POST['id'];
$prov = $_POST['prov'];
$kab_kot = $_POST['kab_kot'];
$eko = $_POST['eko'];

$sql = "UPDATE ekonomi SET prov='$prov', kab_kot='$kab_kot', eko='$eko' WHERE id=$id";

if ($conn->query($sql) === TRUE) {
  echo "Record updated successfully";
} else {
  echo "Error updating record: " . $conn->error;
}

$conn->close();

header("Location: insert.php");
exit();
?>

Explanation

  1. Database Connection: Connects to the MySQL database using the credentials provided.
  2. Form Data: Retrieves the form data using the $_POST superglobal.
  3. SQL Query: Constructs an SQL UPDATE query to update the record in the ekonomi table with the specified ID.
  4. Error Handling: Checks if the query was successful and displays an appropriate message.
  5. Redirection: Redirects back to the `insert

.php` form after submission.

Conclusion

Congratulations! You have successfully created a dynamic form with dropdowns for selecting provinces and cities in Indonesia. This form allows users to insert and update data in a MySQL database. For further learning, you can explore more about PHP and MySQL on W3Schools.

Feel free to experiment with the code and add more features as needed. Happy coding!