Send URL request using PHP and SQL

Tutorials and guides for Plazma Burst and community features.

Send URL request using PHP and SQL

Postby phsc » 18 July 2020, 09:54

INTRODUCTION
This is going to be a tutorial focused on explaining how to request URL pages that run a PHP script, giving some examples of what you can do with it and how, and also talking about how to correlate it with SQL, touching HTML and CSS during that.

This tutorial uses multiple images and open source maps, and some base example code to explain how things work, it is going to be mainly separated in three parts, the foundations, the PHP, and the PHP+SQL, the general idea is that the first part is going to be about what you need to make this work, and how I have used it, the second part explains how to use the .php URLs to do whatever you want, and the third part is going to focus on working with databases, then I will make some final notes and that is all.
What can you do with this, you might ask? you can create a MMO map similar to max teabag-mmo, in a way I believe is much simpler and easier (to an extent, if you know what you are doing) than Max Teabag did (using ASP.NET and a ton of other things), I myself have used that for my chrome dino no internet game map and the website I made for it, but that is pretty simplistic compared to what is possible to be done, I plan on using it again in the future for a multitude of things.

First let me explain some important basic concepts and definitions, kind of a FAQ:
What is an URL? it is pretty much a way of accessing a web address, what is a request? it is literally that, you are going to request the result of that page based on what you information you send, well, you kind of need a server for this, and in this I will be using 000webhost which is a free website hosting website, it works pretty well, other alternatives would probably either be paid or more complicated, hosting yourself is also pretty viable but it probably requires you to know what you are doing.
What is PHP? PHP is a scripting language that runs on a server, while something on the lines of Java or C runs on your computer, this allows PHP to be used online, it is a very high level language (high level meaning easier for human interaction in computer science, while lower level is more complicated), and it is the most important part of this tutorial, if you want to learn PHP: here you can find a simple tutorial and all the documentation for the language, w3schools has some nice content on it as well, which also gets into mixing with some of the other content I will mention in this tutorial.
What is SQL? Structured Query Language is a language used for managing data, pretty much it, there is a ton of ways of using it, if you want to learn SQL: w3schools also has content on it and it is very great.
What is HTML? HyperText Markup Language is the language used for web pages, you write a code that does something and configure it, and it does that thing, that is pretty much it, it is often used with JavaScript and CSS.
What is CSS? Cascading Style Sheets is a language used basically always for making things in HTML better, mostly when it comes to visuals and specific styles and quality of life, HTML is the core, CSS is the visuals, JavaScript is the coding that runs in your computer and PHP is the coding that runs in the server, while SQL is where the stuff is stored, that is how the vast majority of the internet works. if you want to learn HTML and/or CSS: w3schools also has that covered, HTML and CSS.
I will only teach the basics in this tutorial, you might not need to learn much more and just go by what you learn here, but that greatly depends on what you want to do with all of this.

PART 1: FOUNDATION
You need a way to host a website. As I mentioned there are many ways, I will make this tutorial using 000webhost, so I am going to explain how to create an account and a website on it, you will also need a way of hosting and editing the SQL stuff, 000webhost also covers that using an online version of phpMyAdmin, I will put this part under a spoiler tag because not everybody might be interested in it:
HOW TO SETUP THE BASICS OF 000WEBHOST:
Spoiler: Show More
Open the URL I sent, https://www.000webhost.com/ and well, create an account with the free plan, if want to pay for one of the plans they offer, go ahead?


After that, either log in with Google or Facebook if you wish to, or create an account, I am not going to create a new account for this tutorial because: IN AROUND 1-2 YEARS AFTER THE ACCOUNT IS MADE, if you go inactive, they will send an email talking about deleting it, if you do not reply, after some months the account will be deleted and you will lose everything.
After that, verify your email and then log in into your account, and choose the other option as shown here:

Skip the chrome ad.
This here is very important, name your website something you are going to remember and works well in the URL since as far as I know you cannot change the URL, I will name the one I will be using pb2tutorial, the URL will be http://pb2tutorial.000webhostapp.com/ and also remember the pass in some way or set it to something different.
Choose the Upload your site option


this page and click on the following option:

After clicking manage website you will go to your website's page, where you can see statistics and how much space you are using and all, this is pretty much the website's core page, within this there are two important sections:

The file manager is where you upload and edit your PHP files or the HTML files, so the JavaScript and the CSS as well, I will go over it later.
The Databases are pretty much the same thing, the MySQL database not only answers the question of what commands are going to work and what exactly we are dealing with, but it also allows you to get vital information, such as the name of the database, a valid user of the database, the host, and also the password, but we will get into that later.

So you have these two folders, what matters is public_html since the files there are going to be public, a small example I made:
http://pb2tutorial.000webhostapp.com/hellothere.html
Try doing something like that if you are unsure about how things work.
And that should be it for how to use 000webhost.

PART 2: PHP
You will need a way to host a .php file, in this part I will explain how to link it with PB2 and how to use it for some basic concepts.
HOW TO CREATE A PHP FILE IN 000WEBHOST:
Spoiler: Show More
Go into the file manager, https://files.000webhost.com/ if you already are logged should work.
public_html for Public HTML URLs so PB2 can check them:

Create a new file with any name you want, for this first example I will use helloworld.php

Double click it, or select it and click the edit option, and this should appear:

You can also drop files here, but I think that editing directly into it works pretty well and is in a general way faster, I will include the html code in another spoiler box.
HTML code for the hello world HTML tutorial:
Spoiler: Show More
Code: Select all
<html>
<head>
<title>Hello there!</title>
<style>
    .cambria {
        font-family: "Cambria", Cambria, cambria;
    }
</style>
</head>
<body>
<p class="cambria">
    <h1>Hello there!</h1>
</p>
</body>
</html>

2.1: HELLO WORLD
This is the most basic PHP script, it will simply reply "hello world!", but with this I will explain the trigger action.
Resources for this:
Explanation:
<?php indicates it is a php script, ?> indicates the script has enteded, it still has to be a .php file, echo is the most basic command which simply says something:
echo X;
where X is anything, a value? it works, a string? it works, a variable? it works, even objects and more advanced things, in this example "hello world!" is a string, but you could do $helloworld = "hello world"; and then echo $helloworld;
PB2 is simply going to take the result from the URL you put there, so with this you will get whatever is echoed, so this is how you put values out.
Inside the map, it is pretty easy to understand, #region*1 is going to call trigger #send*url which is going to set the variable var_url to http://pb2tutorial.000webhostapp.com/helloworld.php, and use op189 also known as "URL > Request webpage with URL stored in variable 'A' and save response to variable 'B' once loaded (variable 'B' will be equal to "loading..." for some period of time)", with A being var_url and B as var_response, which will make var_response turn into "loading..." then into "hello world!" once it loads, #timer*1 and the trigger #show*response only constantly check for the value of var_response.

2.2: CHECKING PING VALUES
This is just a basic map to check the delay, the script is exactly the same but it is very useful to see how long it takes for your server to do what you want.
Resources for this:
Explanation:
This is pretty simple as well but more so you can get the idea of the quality of your servers in correlation with users, the timer #constantsend is going to call the trigger #sendrequest with a delay of 1 from the start, such trigger resets the value of var_response and var_counter (the variable for the ping value), it requests the webpage in var_url which is the same that was used last time, activates the timer #constantrequest and deactivates the timer #constantsend and the trigger #sendrequest as well, #constantrequest also calls with a delay of 1, since 1 second = 30 in the delay value, 1 is 1/30 of a second, #constantrequest calls #checkrequest, which is going to add one to var_counter, and verify if var_response loaded (if it is not "loading..."), it is going to divide var_counter by 30 and multiply it by 1000, using a delay of 1 second, var_counter would be 30, 30/30 is 1, so 1 second, that multiplied by 1000 gets the milisecond value, which is the ping value, the value is rounded because the division by 30 gets some not so great values, and since this is not the exact value since I don't know how often a value of 0 calls and you cannot do decimal values like 0.5, after that it shows the value on the interface as a hint, #constantrequest is disabled and both #constantsend and #sendrequest are activated, looping the system.

2.3: GENERIC PHP
This is some generic PHP stuff, some examples of some things you can do, some commands and all, it is very similar to C/C++/C# or Java in general, and this shows it pretty well.
Resources for this:
Spoiler: Show More
Map Page Demo Link Level Editor
URL: http://pb2tutorial.000webhostapp.com/generic.php
Code:
Code: Select all
<?php
    error_reporting(true);
    function isValid($string) {
        return !preg_match('/[^A-Za-z0-9.#\\-$]/', $string);
    }
    function Fibonacci($n){
        if ($n <= 1)
            return $n;
        else
            return Fibonacci($n - 1) + Fibonacci ($n - 2);
    }
   
    $option = $_GET['option'];
    $number = $_GET['number'];
    $login = preg_replace("/[^a-zA-Z0-9\s]/", "", $_GET['login']);
    $username = $_POST['user_login'];
   
    switch ($option) {
    case "fibonacci":
        if (is_numeric($number) == true){
            $number = abs($number);
            $c = 0;
            while ($c < $number){
                $result = Fibonacci($c);
                $c++;
            }
            echo $result;
        } else
            echo "-1";
        break;
    case "datetime":
        $date = file_get_contents("https://www.plazmaburst2.com/date.php?format=d.m.Y_h.i.s");
        $year = strval(substr($date, 6, 4)); $month = strval(substr($date, 3, 2)); $day = strval(substr($date, 0, 2));
        $time = str_replace(".",":",strval(substr($date, 11, 8)));
        echo  $year . "-" . $month . "-" . $day . " " . $time;
        break;
    case "datetime2":
        echo file_get_contents("https://www.plazmaburst2.com/date.php?format=Y-m-d%20h:i:s");
        break;
    case "month":
        echo file_get_contents("https://www.plazmaburst2.com/date.php?format=F");
        break;
    case "username":
        echo $login;
        break;
    case "username2":
        echo $username;
        break;
    case "info":
        echo $_POST['user_uid'] . " AKA " . $_POST['user_login'] . " in " . $_POST['map_id'];
        break;
    default:
        echo "error";
    }
?>
Explanation:
This has two parts to it, the PHP code and the map, lets start with the php code:
error_reporting() is a procedure which defines if PHP is going to send error messages or not, it is true in this case and it is true by default, because this is a tutorial, but in actual code you use in PB2 you might want to turn it off because PB2 is going to include the error message content in the URL response.
function indicates something is a function which you can call at some point, isValid is the name of the function, it returns a boolean value for the function preg_match which is inverted with !, just like != inverts the = signal, ! for a boolean value inverts it's value to the opposite, isValid ($string), if the string has the concents of preg_match mentioned there, it is going to send a false message, while naturally preg_match only checks if characters are in such string, you can read more on preg_match here.
function Fibonacci($n) is another function where $n is an integer, it does the fibonacci series using recursion which is a concept and method of executing it, it is not particularly the most effective one for PHP but I used it because it is short, it would be more effective to make one without recursion, this shows that you can do some stuff that is pretty complicated to do in PB2 with programming and also gives some information for programmers unfamiliar with PHP who are reading this, if is the typical checking for a condition and executing a thing or not, if a if check does not happen or other if checks do not, else runs.
$option, $number, $login and $username are variables which get their $_GET values, with the exception of $username which is a $_POST, what $option = $_GET[] does is get HTML form data, but it does not have to come from HTML forms, it originally was made for it, I will not explain this deep but POST is a more secure method of sending information since it does not show in the URL, but it is harder to check for at times, while GET shows and in general is more practical, only staff should really get access to a map of yours so use GET, but PB2 sends some POST requests, you can learn more on it by searching on both methods, if you add ?option=datetime to the URL like http://pb2tutorial.000webhostapp.com/ge ... n=datetime, you can see that it gets the time from PB2s server, what happens is that, $option gets the value of option from the URL, which would be something different in HTML forms that would lead to such URL, $number does the same for the number parameter, you can do http://pb2tutorial.000webhostapp.com/ge ... &number=30 and $number will be 30, in the case of $login preg_replace checks for the content in it's first parameter (it's a function) and swaps that out for the second parameter, which is "", which is an empty string, and does that for the values of the login GET, the reasons why are security reasons, which are much more important when it comes to SQL so I will explain why there, $username does the same for POST, but user_login comes from PB2 itself, there are three options you can get by default, for other information you will need the API key from Eric Gurt, which I do not have access to, there is a forum tutorial explaining how to use it, the three options are map_id, user_uid and user_login, every time you activate the trigger, that is sent, but you might just not use it, it should be fairly obvious what they are, map ID, user ID and login, you can get more info on them here.
switch checks for multiple options under a specific variable, like a ton of ifs, like instead of if (X==1) {} else if (X==2) {} else if (X==3) {} else {] you can do switch (X) case 1: break; case 2: break; case 3: break; default: }, break; stops a loop like a while or for, or a check like an if or switch, it is needed otherwise all cases execute, if you put a case as blank, it will just skip it, default: is the default case, and it checks for the value you submit for $option, there are eight options: fibonacci, datetime, datetime2, month, username, username2, info and default, so lets see what happens in each case:
fibonacci: If the number submitted is... numeric, which means it has numbers, using the function is_numeric(), it gives $number its absolute value using the function abs() which means it makes it positive, because you cannot do the fibonacci series with negative numbers, and $c is a generic counting variable, it runs Fibonacci() until it does the mathematical function the same amount of times that is requested using the while() loop, that being $number, the result constantly goes to $result, and $c++ adds one to the value of $c, at the end of the loop, it shows $result, which PB2 is going to read, in case it somehow fails, the else case, it shows -1, which is not part of the fibonacci series.
datetime: It gets the date value from PB2s date API, which can be configured to any format, $date gets the value of the webpage present within file_get_contents(), which is the content, it is a PHP file that shows the date that the PB2 servers run on, you can change the format to anything, I will show that later with other examples, you can see everything you can request within the format here.
$year, $month and $day will be specific parts of $date, separated with $substr(), which takes a part of the string, start at the beggining of character 0, and going the second parameter into the string, $day gets substr("18.06.2020_01:35:45", 0, 2), which takes only "18" from the variable, $month does that but it would start at before 0 and end at before ., since it only checks for 2 digits, and that is how it goes.
$date is a string where the format is updated to fit the MySQL DATETIME variable format, which is YYYY-MM-DD, so $year . "-" . $month . "-" . $time just adds one string to another and another, . adds one string to another, and that value is shown since this is just a tutorial.
datetime2: Does the exact same as datetime, but it just changes the formatting directly on the PB2 date.php file, which you can read more on the page I linked that talks about the POST values you can get from PB2, it has a page of it's own inside of it, %20 just means " ", the space character.
month: Does the same but only gets the month and shows it, to show it is not limited to such formats.
username: Shows the value of the variable $login, which is the one you sent via GET.
username2: Shows the value of the variable $username, which is the one PB2 sent via POST.
info: Shows all the POST information you can get from PB2, you can get much more information in other methods, such as using hte PB2 API with the needed key or by doing web scrapping or simply doing file_get_contents() for a PB2 URL, but keep in mind not a ton of info is possible to be found without logging into an account.
default: Echoes "error" since it is not supposed to happen!
And that is the generic PHP script fully explained, now lets get to the map!

All of the 8 regions, decors, triggers, triggers over the other triggers and timers do the same and are pretty intuitive and easy to understand, I will be explaining the first valid example, which is #option*1 which triggers #send*url*fibonacci, but before that, #timer*declaration calls the trigger #declaration which sets the value of var_url to the location of our PHP script, and explains what each trigger does by changing the text decoration over them to their respective values.
#send*url*fibonacci is going to set the value of variable var_infourl to option=fibonacci&number=, then add var_infourl to the end of var_url, then randomize a number betwen 0 and 9 (0 and B-1) to var_random, add one to it since you cannot do 0 numbers for fibonacci, then add it to the end of var_url, it will request the webpage in var_url then change var_url to its original value, activating #timer*show*decor*text*otion*fibonacci and deactivating itself, #send*url*fibonacci. Such timer will call #show*decor*text*option*fibonacci every 1/6 of a second which is going to set the value of the decoration #decor*text*option*fibonacci to the value of var_response, which just like in the previous examples is the response value for the URL, and if var_response is NOT "loading...", then it deactivates the timer that called it, #timer*show*decor*text*option*fibonacci and reactivates the original trigger #send*url*fibonacci.
So it checks if it has replied, if it does not reply, you cannot activate it, keep in mind that you can activate other triggers while this is still being sent which changes the result value, since it uses the same response variable for all actions, which can be easily fixed by changing the name of each variable to something else.
And extremely similar cases for every other single trigger present in the map for the other options present in that switch() for $option.
And this should be the basics of PHP in correlation with PB2, now to the SQL part.

PART 3: SQL
You will need a way to host a database, in this part I will explain how to create one and use it together with PHP
HOW TO CREATE A DATABASE IN 000WEBHOST:
Spoiler: Show More
Go to your dashboard, I've shown how to do that before, then go to:

Put in the information you want, I will be using this, save that password since you will need it later, but it is pretty easy to change, this is my database for these tutorials:

Useful/important information:

This is mine:

Clicking on Manage opens this:

I will be using PhpMyAdmin, as far as I know it is not needed after this, you can connect and do the commands already, like CREATE DATABASE and CREATE TABLE and all, but PhpMyAdmin makes that easier and more convenient for me and probably is going to do the same for beginners.
I will be creating a new table called userinfo:

I already created it and all you need to know is that I selected PRIMARY KEY for id, a primary key is an unique field, which is used to identify things, A_I is AUTO_INCREMENT which means it will... auto increment! every time a value is inserted it increases X in value, the default is 1, that + primary key makes so you can just not set a value for id constantly, if you want to reset it, you can do ALTER TABLE tablename AUTO_INCREMENT = 1.

A bit of an explanation, INT is the typical integer, VARCHAR() is a string, 32 is as far as I know the limit for login names in PB2, DATE is DATETIME which has the following formatting: YYYY-MM-DD.
Now the database is ready, it already is running, you can use the SQL section to make commands, to check for its contents, either select database>userinfo and go to Structure, or go to SQL and run a SELECT, if you want to SELECT everything you can do SELECT * FROM table, in my case SELECT * FROM userinfo.
And now you have a database.

3.1: INSERTING VALUES
This is just a basic map to check the delay, the script is exactly the same but it is very useful to see how long it takes for your server to do what you want.
Resources for this:
Spoiler: Show More
Map Page|Demo Link|Level Editor
URL: http://pb2tutorial.000webhostapp.com/insert.php
Code:
Code: Select all
<?php
    function isValid($string) {
        return !preg_match('/[^A-Za-z0-9.#\\-$]/', $string);
    }

    error_reporting(true);
   
    $servername = "localhost";
    $username = "id14343539_phsc";
    $password = "XXXXXXXXXXXXXX";
    $database = "id14343539_pb2tutorialdatabase";
   
   $conn = new mysqli($servername, $username, $password, $database);
    if ($conn->connect_error)
        die("Connection failed: " . $conn->connect_error);
       
    $login = $_POST['user_login'];
    $uid = $_POST['user_uid'];
    $value = $_GET['value'];
    $date = file_get_contents("https://www.plazmaburst2.com/date.php?format=Y-m-d");
   
    if ($login != null && $uid != null && value != null){
        $command = "INSERT INTO userinfo (login, uid, value, creationdate) VALUES ('" .
        $login . "'," . $uid . "," . $value . ",'" . $date . "');";
        $conn->query($command);
        echo "Inserted values " . $login . " " . $uid  . " " .  $value  . " " . $date . " with success.";
    } else echo "Insert failed.";
    $conn->close();
?>
Explanation:
Let's start with the code again, I won't explain things that I have explained before, $servername, $username, $password and database are information fields, put the information you got from your database there, if you are using 000webhost you should have these values since I told you to save them, put them there, I am not going to show the password because I do not want people breaking my database for this tutorial, not a very cool thing, $conn is the object which is going to be used to connect with the MySQL database, you can put the information directly there, after that it checks if there was a connection error, if there was one, the program stops with die() and says "Connection Failed: " with the specific connection error.
$login, $uid are getting the POST data PB2 sent, $value is GETting the data PB2 sent, $date is checking the current date, this gets into an if with multiple parameters, is $login empty? is $uid empty? is $value empty? if they all (&& means AND, || means or) are not null, things are fine to go, and we get into the actual SQL command, $command is going to INSERT INTO userinfo (login, uid, value, creationdate) VALUES ('your login', your UID, the value, 'the date'), the specific fields selected to put it in order and you need to put the strings together like that because if you put them directly into ' or " it is going to read as pure text, so instead of your login, the actual text $login will be inserted into the database, the ' are going to indicate a thing is string text while " indicates it is a string variable, after all.
$conn->query($command) executes that query, and the echo shows the values, if the values are not null, this is an example, you might want to check for the errors that PB2 sends via the POST method, and create specific situations for that, $conn->close() closes the connection.

Now to the map itself, it is very simple, #region*1 calls trigger #insert which has var_url with the URL we are using + ?value= and it sets the value of var_value to a random integer betwen 0 and B-1, with 1000 as the maximum value, adds one to it so it is 1 to 1000, adds var_value to the end of var_url, requests var_url, activates that exact same system that checks if it is going to load or not, simple as that.

3.2: SELECTING VALUES
This is just a basic map to check the delay, the script is exactly the same but it is very useful to see how long it takes for your server to do what you want.
Resources for this:
Spoiler: Show More
Map Page|Demo Link|Level Editor
URL: http://pb2tutorial.000webhostapp.com/select.php
Code:
Code: Select all
<?php
    error_reporting(true);
   
    $servername = "localhost";
    $username = "id14343539_phsc";
    $password = "XXXXXXXXXXXXXX";
    $database = "id14343539_pb2tutorialdatabase";
   
   $conn = new mysqli($servername, $username, $password, $database);
    if ($conn->connect_error)
        die("Connection failed: " . $conn->connect_error);
     
    $option = $_GET['option'];
    switch ($option) {
    case "login":
        $login = $_POST['user_login'];
        $command = "SELECT login, uid, value, creationdate FROM userinfo WHERE login = '" . $login . "';";
        $result = $conn->query($command);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo $row["login"] . " " . $row["uid"] . " " . $row["value"] . " " . $row["creationdate"] . " ";
            }
        } else
            echo "0 results";
        break;
   
    case "uid":
        $command = "SELECT login, uid, value, creationdate FROM userinfo WHERE uid = " . $_POST['user_uid'] . ";";
        $result = $conn->query($command);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo $row["login"] . " " . $row["uid"] . " " . $row["value"] . " " . $row["creationdate"] . " ";
            }
        } else
            echo "0 results";
        break;
   
    case "value":
        $command = "SELECT login, uid, value, creationdate FROM userinfo WHERE value = " . $_GET['value'] . ";";
        $result = $conn->query($command);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo $row["login"] . " " . $row["uid"] . " " . $row["value"] . " " . $row["creationdate"] . " ";
            }
        } else
            echo "0 results";
        break;
   
    case "date":
        $command = "SELECT login, uid, value, creationdate FROM userinfo WHERE creationdate = '" . file_get_contents("https://www.plazmaburst2.com/date.php?format=Y-m-d") . "';";
        $result = $conn->query($command);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo $row["login"] . " " . $row["uid"] . " " . $row["value"] . " " . $row["creationdate"] . " ";
            }
        } else
            echo "0 results";
        break;
   
    default: "Select failed.";
    }
   
    $conn->close();
?>
Explanation:
Same initial stuff as last part, switch case for what option to select based on, search that in part 2.3 if you want to understand that feature of PHP, command this time is SELECT login, uid, value, creationdate FROM userinfo WHERE login/uid/value/creationdate = $login/$uid/$value/file_get_contents("date.php?format=Y-m-d"), each one for their respective case, you can use the POST or GET directly into the command as you can see, the only thing that differs is that if, if the number of rows is > 0 for $result, which holds the results for the query we ran, which is a special array, you check every single thing that was selected with that while, and fetch_assoc(), which is getting something from the associative array, the special array, $row indicates what to get since it is checking everything with fetch_assoc(), row["login"] gets the current login, and that is how it goes, and echoes all of it, and that repeats 3 times for other variables, in pretty much the same way.

In the map itself, I made things slighty different this time, #region*1 calls the trigger #information which explains how it works, now this is using text commands, #initial_timer calls #variable*declaration which sets some of the typical stuff, var_url, the trigger #text*trigger as the text receiver, var_additionaltext to &value= and the value of variable var_value to 500, #text*trigger sets var_text to text being said, and it checks for the following commands: login, uid, value and date, if the text said fits any of these values, it runs #option*X where X is each of these commands names, which define what option is going to be used, you can even add var*text directly to the end of var_url, after this it does the general verification for it things work or not, and if there is a response #trigger*response will show it ingame as a message, the only difference in the other 3 options is that #option*value will also add both var_additionaltext and var_value to the end of var_url, and that is it, you selected the data and it is showing in PB2.

3.3: MAKING A WEBSITE
This one is not going to involve PB2 again, you can do this if you want to select values into a website using HTML, the example is going to be very basic but out of this you can learn more.
Spoiler: Show More
URL: https://pb2test.000webhostapp.com/dino.php
Code:
Code: Select all
<html>
<head>
    <style>
        .serif {
            font-family: "Cambria", Cambria, serif;
        }
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
            border-color: #808080;
        }
    </style>
    <title>phsc-dino scores</title>
</head>

<body>
<?php
    error_reporting(false);
   
    $servername = "localhost";
    $username = "XXXXXXXXXXXX";
    $password = "XXXXXXXXXXXX";
    $database = "XXXXXXXXXXXX";
   
    $conn = new mysqli($servername, $username, $password, $database);
    if ($conn->connect_error)
        die("Connection failed: " . $conn->connect_error);
       
    $command = "SELECT id, login, date, nscore, score FROM dinomapinfo;";

    $result = $conn->query($command);
    echo '<p class="serif"><table style="width:100%">';
    echo '<tr style="background-color:#BBBBBB"><th>ID</th><th>LOGIN</th><th>DATE</th><th>SCORE</th><th>NSCORE</th></tr>';
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo '<tr style="background-color: #EEEEEE"> <th>' . $row["id"] . "</th><th>" . $row["login"] .
            "</th><th>" . $row["date"] . "</th><th>" . $row["score"] . "</th><th>" . $row["nscore"] . "</th></tr>";
        }
    } else {
        echo "0 results";
    }
    echo '</table></p>';
    $conn->close();
?>
</body>
</html>
Explanation:
There is no map this time, so I will break down the HTML and CSS parts a bit, it is very simplistic and short but it can be good to at least make those who are curious comfortable.
<html> starts the indication for the HTML code, modern versions use doctype but this is not necessary, <head> indicates the start of the head section, where we can add <style> to customize things a bit with CSS, using .serif to define a font, in this case Cambria, and customize the looks of <table> and its friends, making it's border thin, changing its style and changing its color, as well as setting the <title> to phsc-dino scores, because this is the scores page for my dino map, which I used this exact code to save highscores.
<body> starts the body section where the actual webpage goes, but we won't be using a normal webpage, this is going to be all created according to the situation with PHP.

You can echo HTML codes to allow it to create an adaptative webpage for what you are doing, what I did is very simplistic and only shows the scores, but you can have this on an actual website, since this is something I use I did not give my $username and $database values for security reasons, which brings me to a point: SECURITY!

Eric Gurt, the man himself, sent me a Discord message with some important information:
Spoiler: Show More
Out of that we can know that, hacking variables is possible, or at least passing values is, so security is an important thing, this is why I also added some things to remove characters such as * or // or " or ', which can change the way the manipulation of the SQL works, this can generate a big problem which is known as SQL injection, where you inject commands inside of such values, there are many ways of solving that, Eric in his message talks about some, I do think that you do not need to go very far and that if you only allow specific characters to be inserted, things should be fine, this is what isValid() exists for, as well as preg_replace() and why I explained them, it is important, you can also do what Eric says which brings even more security, but I do think that what I did is fine as well, and there are commands like DROP and DELETE DATABASE which are not the nicest, but not only such extreme commands, simpler ones such as ALTER or even INSERT can cause a lot of damage.
If you want more information on security, you can use prepared statements/parameterized queries, https://stackoverflow.com/questions/601 ... ion-in-php goes over that pretty well, PDO (PHP Data OBjects) is another way of handling databases with PHP, you can learn about that as well since it is a bit simpler to use I would say, some other security tpyes is casting the variable types, handling an user ID? you can
$safe_userid = (int)$userid, (int) makes sure it is an integer, the way I did it is probably the worst since it allows people to insert scores as other people if they create an account like phsc// or /phsc, but that really should not be an issue in my case, but it might be in yours, if you want to create something where users can actually lose things, use prepared statements since they are the most safe method, in my case I also used preg_replace() because of possible HTML codes that can be inserted and break the webpage, yes, webpage!

Back to it, what I am doing is using the echo command to add HTML tags to the page, such as <br> to skip lines, <table> to start a table, <p class="serif"> to define the font, at first it defines the font and that it is a table, the second echo defines the first row of the table, which is where the explanation of what everything is goes, also giving it a different background color, then every time I get a value from the database, and then it just echoes the values, just like in the SELECT tutorial, but instead of PB2, it goes to a webpage.

FINAL NOTES
And this should be pretty much all, you can do literally anything with this, this is just the basics, I sent some links at the start but every programmer has to know about this one, Stack Overflow where you can ask questions and search for questions, you can also use Google to search for ways to do things you want, or just try to create it, but this is just an introduction and the basics.
If you have any doubts just ask on this post, want help? just explain your problem to me on PB2s Discord, or send me a PM in PB2, or just explain it here, I believe this post is more informative and better for beginners than what Max Teabag made, as much as he did it with a video, it seems like he does not really understand what he is doing and he kind of even admits to that! which does not mean I am a master programmer, but I do have a technicians degree and I had formal classes, including classes on PHP, HTML, SQL and CSS classes!
Also, the account with all the maps used in this tutorial is php html sql css, but send messages to phsc
User avatar
phsc
Noir Lime [600]
 
Posts: 694
Joined: 27 July 2013, 13:58
Location: Brazil

Return to Tutorials

Who is online

Users browsing this forum: No registered users



cron