Server-Side Scripting/NoSQL Databases/PHP

From Wikiversity
Jump to navigation Jump to search

index.php[edit | edit source]

<?php

// This program creates and displays a temperature database
// with options to insert, update, and delete records.
//
// References:
//  https://en.wikibooks.org/wiki/PHP_Programming
//  https://www.php.net/manual/en/class.mongodb-driver-manager.php
//  http://zetcode.com/db/mongodbphp/

$HOST = "mongodb://localhost";
$DATABASE = "temperature";
$COLLECTION = "countries";

$FORM = '
<h1>Temperature Data Entry</h1>
<p>Enter country and temperature. Enter again to update.</p>
<p>Enter country without temperature to delete.</p>
<form method="POST">
<p><label for="country">Country:</label>
<input type="text" id="country" name="country" required></p>
<p><label for="stop">Temperature:</label>
<input type="text" id="temperature" name="temperature"></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
<hr>
';

main();

function main() {
    switch($_SERVER["REQUEST_METHOD"]) {
        case "GET":
            try {
                echo $GLOBALS["FORM"];
                echo get_data();
            } catch (Exception $exception) {
                echo $exception->getMessage();
            }
            break;
        case "POST":
            try {
                $country = $_POST["country"];
                $temperature = $_POST["temperature"];
                if (!country_exists($country)) {
                    insert_country($country, $temperature);
                } else if ($temperature != "") {
                    update_country($country, $temperature);
                }
                else {
                    delete_country($country);
                }

                echo $GLOBALS["FORM"];
                echo get_data();
            } catch (Exception $exception) {
                echo $exception->getMessage();
            }
            break;
        default:
            echo "Unexpected request method:" . $_SERVER["REQUEST_METHOD"];
            break;
    } 
}

function get_data() {
    $filter = [];
    $manager = new MongoDB\Driver\Manager($GLOBALS["HOST"]);
    $query = new MongoDB\Driver\Query($filter);
    $cursor = $manager->executeQuery(
        $GLOBALS["DATABASE"] . "." . $GLOBALS["COLLECTION"], 
        $query);
    
    $result = "<table><tr><th>ID</th>";
    $result = $result . "<th>Country</th>";
    $result = $result . "<th>Temperature</th></tr>";
    foreach ($cursor as $document) {
        $result = $result . "<tr><td>" . $document->_id . "</td>";
        $result = $result . "<td>" . $document->country . "</td>";
        $result = $result . "<td>" . $document->temperature . "</td></tr>";
    }
    $result = $result . "</table>";
    return $result;
}

function country_exists($country) {
    $manager = new MongoDB\Driver\Manager($GLOBALS["HOST"]);
    $query = [
        "country" => $country
    ];
    $count = [
        "count" => $GLOBALS["COLLECTION"],
        "query" => $query
    ];
    $command = new MongoDB\Driver\Command($count);
    $cursor = $manager->executeReadCommand(
        $GLOBALS["DATABASE"],
        $command);
    $result = current($cursor->toArray())->n;
    return !!$result;
}

function insert_country($country, $temperature) {
    $manager = new MongoDB\Driver\Manager($GLOBALS["HOST"]);
    $bulk = new MongoDB\Driver\BulkWrite;
    $document = [
        "country" => $country,
        "temperature" => $temperature
    ];
    $bulk->insert($document);
    $manager->executeBulkWrite(
        $GLOBALS["DATABASE"] . "." . $GLOBALS["COLLECTION"], 
        $bulk);
}

function update_country($country, $temperature) {
    $manager = new MongoDB\Driver\Manager($GLOBALS["HOST"]);
    $bulk = new MongoDB\Driver\BulkWrite;
    $filter = [
        "country" => $country
    ];
    $update = [
        '$set' => [ "temperature" => $temperature ]
    ];
    $bulk->update($filter, $update);
    $manager->executeBulkWrite(
        $GLOBALS["DATABASE"] . "." . $GLOBALS["COLLECTION"], 
        $bulk);
}

function delete_country($country) {
    $manager = new MongoDB\Driver\Manager($GLOBALS["HOST"]);
    $bulk = new MongoDB\Driver\BulkWrite;
    $filter = [
        "country" => $country
    ];
    $bulk->delete($filter);
    $manager->executeBulkWrite(
        $GLOBALS["DATABASE"] . "." . $GLOBALS["COLLECTION"], 
        $bulk);
}

?>

Try It[edit | edit source]

Copy and paste the code above into the following free online development environment or use your own PHP compiler / interpreter / IDE.

  • None