feat: Add new mobs to database

This commit is contained in:
overflowerror 2024-07-27 18:05:18 +02:00
parent c242caea11
commit 0b72962ce5
5 changed files with 41 additions and 3 deletions

3
.gitignore vendored
View file

@ -1 +1,2 @@
.idea
.idea
credentials.php

View file

@ -36,8 +36,14 @@ $mobs = array_reduce($mobs, function ($mobs, $mob) {
}, []);
echo "Downloading images...\n";
foreach ($mobs as $mob) {
foreach ($mobs as &$mob) {
echo " ... " . $mob["name"] . "\n";
$filename = downloadImage($mob["image"], $mob["name"]);
$mob["filename"] = $filename;
var_dump($mob);
}
echo "Adding to database...\n";
foreach ($mobs as &$mob) {
echo " ... " . $mob["name"] . "\n";
addOrUpdateMob($mob["name"], $mob["filename"]);
}

7
credentials.templ.php Normal file
View file

@ -0,0 +1,7 @@
<?php
const POSTGRES_HOST = "%DBHOST%";
const POSTGRES_PORT = 5432;
const POSTGRES_DBNAME = "%DBNAME%";
const POSTGRES_USER = "%DBUSER%";
const POSTGRES_PASSWORD = "%DBPASSWORD%";

7
lib/database.php Normal file
View file

@ -0,0 +1,7 @@
<?php
require_once __DIR__ . "/../credentials.php";
$dsn = "pgsql:host=" . POSTGRES_HOST . ";dbname=" . POSTGRES_DBNAME . ";port=" . POSTGRES_PORT;
$pdo = new PDO($dsn, POSTGRES_USER, POSTGRES_PASSWORD);

View file

@ -1,6 +1,7 @@
<?php
require_once __DIR__ . "/request.php";
require_once __DIR__ . "/database.php";
function handleWikiRequest(string $args, bool $rvslots = true): array {
$url = "https://minecraft.wiki/api.php?action=query&format=json&" . $args;
@ -92,4 +93,20 @@ function downloadImage(string $url, string $mobname): string {
fclose($file);
return $name;
}
function addOrUpdateMob(string $name, string $filename) {
global $pdo;
$query = $pdo->prepare("SELECT name from mobs where name = ?");
$query->execute([$name]) or die("unable to check if mob exists");
if ($query->rowCount() == 0) {
$query = $pdo->prepare("INSERT INTO mobs (name, image) VALUES (?, ?)");
$query->execute([$name, $filename]) or die("unable to add new mob");
echo " added\n";
} else {
$query = $pdo->prepare("UPDATE mobs SET image = ? WHERE name = ?");
$query->execute([$filename, $name]) or die("unable to update mob");
echo " updated\n";
}
}