Short answer: no. You need to read it all anyway.
TL;DR
To fully understand the process, it will be necessary to understand several basic concepts that many novice users fail to study. Many of the mistakes made occur precisely because the user does not have full control over what is happening, only replicating codes found in various sources, whether in Stack Overflow, in the official language documentation, or on any websites.
The concepts addressed are:
- Who is client and who is server?
- What is HTTP?
- Building the HTTP request with the form
- Apache and the HTTP request
- And the database?
- Connecting with the database
- Inserting the data into the database
The question focuses on using the PHP language on the server side, but all concepts that will be addressed in the answer will apply to any language; only the codes themselves that will change.
1) Who is client and who is server?
To facilitate the response, we will reduce our domain only to a communication between browser and server, which is the simplest and most common, not going into details about asynchronous requests from Javascript or requests made from the server, as when using Curl, for example.
In the field of Web development, we call as client the browser (browser) - and for user the person making use of the browser. The function in the browser is to interpret a markup language that is more readable to the computer than to humans and render it in a way that is pleasing to humans: HTML. All browsers currently also support a dynamic programming language that allows you to create HTML pages with user interaction: Javascript. And to top it off, there’s still CSS, which is a style language that the browser uses as a reference for rendering HTML. All this occurs in the browser, using the client’s computer, without any dependency on the server. We call this client side, or in English, client-side.
The server is the computer that hosts your application. It is the location that the developer commonly accesses via FTP to upload the files from the site. This computer has an installed program that is called web server who is responsible for managing customers' orders and providing them with a response according to the order, also ensuring that the response reaches the right customer and not just any customer. This program is Apache, or Nginx, or analogues. This program can be configured to work with programming languages, such as PHP, to make the process of creating the response more dynamic - which is why you need a programming language to create dynamic pages. Basically what the web server does is to execute the code written in PHP defining some values that indicate who is the client and what was the request made by this. These values are available in super global variables PHP. Everything that happens in Apache and PHP we say is on the server side, or in English, server-side.
Recommended reading:
Customer-side development is called front-end and server-side development is called back-end.
Recommended reading:
2) What is HTTP?
The Web functions as a question and answer game: one question and the other answers. In the context we are dealing with, the conversation between browser and server, the browser will ask the question and the server will answer. The correct name of this question is requisition and the correct name of this answer is reply same (hehe). And what is the HTTP relation to the request and response? HTTP is the language of this conversation. If one asks the question in one language and the other responds in a different language, do you agree that communication cannot be established? One will not understand the other. But if you use the same language, you will both understand each other and that is what HTTP does. Technically, we call HTTP communication protocol and it’s the medium used by whichever communication between client and server.
- For the browser to open a page it sends an HTTP request to the server;
- For the browser to send form data to PHP it sends via an HTTP request to the server;
- For the browser to display the details of a database movie it sends an HTTP request to the server;
- For the client to update the data in the database via a form is sent via an HTTP request to the server;
But how do I send this HTTP request from the browser? Well, in a way that’s the work of the browser itself. For example, when you create a link on your page, you are telling the browser that it will need to make an HTTP request to the server that hosts the link page using the GET method. The server response to this request will be an HTTP response with an HTML code in its body and it is this HTML code that will be rendered when the browser changes pages. In these cases, HTTP communication occurs "behind the scenes" and the user does not even notice. When the HTTP request starts from a form, be it to register information or just to update it, the HTTP request will be built in the element form
. The attribute action
will define the URL to which the HTTP request will be sent; the attribute method
sets the HTTP method to use for the request. Remember that before I commented that the web server provides some information to PHP through super glbais? It is exactly this information. What Apache does is analyze the incoming HTTP request by extracting this information and passing it to PHP to decide what is the best response to be sent back to the client.
2.1) Building the HTTP request with the form
The question defines the context of registering a post in a blog. For this, we need to define some points:
- Which URL will process the data and register in the database?
- What will be the fields that the user must fill in?
- What is the HTTP method to use?
Which URL will process the data and register in the database?
It depends a lot on how the application is designed, so by way of example I will define that it is a file called cadastrar_post.php
located in the application’s root directory, then the URL will be: /cadastrar_post.php
. With this, we define the value of the attribute action
our:
<form action="/cadastrar_post.php">
...
</form>
What will be the fields that the user must fill in?
This has already been answered in the question and are the title and content fields. The first being a short text and the second being a long text. Thus, we can create the fields as it was also presented in the question:
<form action="/cadastrar_post.php">
<div class="form-group">
<input type="text" class="form-control" placeholder="Título" name="titulo">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Conteúdo" name="conteudo" row='3'></textarea>
</div>
<button type="submit" class="btn btn-default">Enviar</button>
</form>
What is the HTTP method to use?
The HTTP specification recommends using the method POST
when the client sends new data to the server. Therefore, we will use the method POST
, thus defining the value of the attribute method
form:
<form action="/cadastrar_post.php" method="POST">
<div class="form-group">
<input type="text" class="form-control" placeholder="Título" name="titulo">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Conteúdo" name="conteudo" row='3'></textarea>
</div>
<button type="submit" class="btn btn-default">Enviar</button>
</form>
When submitted, the browser will send a similar HTTP request to the server:
POST /cadastrar_post.php HTTP/1.1
Host: ...
Content-Type: application/x-www-form-urlencoded
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...
titulo={titulo}&conteudo={conteudo}
Where {titulo}
and {conteudo}
are the values indicated on the form.
2.2) Apache and HTTP request
The same request above is handled by Apache on the server side, passing to PHP, through the super global variables, the information about such a request. For example, in PHP, if the developer needs to verify which HTTP method was used, simply access the value in $_SERVER["REQUEST_METHOD"]
and the values informed by the user in the form would be available in $_POST["titulo"]
and $_POST["conteudo"]
, so PHP will have enough tools to decide what to do with the information received and, more importantly, indicate to Apache what should be the response that will be delivered to the client back. Apache will analyze this information passed by PHP and generate the HTTP response it sends to the browser.
For data validations coming from HTTP, you can use the function filter_input
.
Assuming the PHP page was something like:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "<h1>" . $_POST["titulo"] . "</h1>";
echo "<p>" . $_POST["conteudo"] . "</p>";
}
The HTTP response that would be generated would look like:
HTTP/1.1 200 OK
Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
Content-Type: text/html; charset=UTF-8
Content-Length: 34
<h1>{titulo}</h1>
<p>{conteudo}</p>
The browser, receiving this response, will scan it and display the HTML code. Note that PHP code is not part of the HTTP response; it is only used to generate the response. The browser does not have access to PHP code and that is why when it is necessary to do some client-side interaction it is necessary to use Javascript and no longer PHP.
Recommended reading:
3) And the database?
Now that we know exactly how the client and the server communicate we can worry about developing the rules of the application. In PHP there are numerous ways to work with databases. It will depend mainly on which database you are working with. As specified in the question, the database will be Mysql and for this PHP already has a native API: a Mysqli. This API allows you to both use the procedural form as to object oriented. In this answer I will focus attention on procedural use, because I see no need to use object oriented but together with an application that uses the same paradigm.
3.1) Connecting with the database
To make the connection to the database, we use the function mysqli_connect
, it receives as parameters:
- host: database server name;
- username: bank access user name;
- password: bank access user password;
- dbname: name of the database;
There are two other parameters that are less used and are described in the official documentation. Moreover, all parameters are optional.
So, to connect to the local server, we can do:
<?php
$mysqli = mysqli_connect("localhost", "root", "admin", "blog");
However, doing this alone does not guarantee that the connection is successfully made. To handle possible errors, just use the functions mysqli_connect_errno
and mysqli_connect_error
.
<?php
$mysqli = mysqli_connect("localhost", "root", "admin", "blog");
if (mysqli_connect_errno($mysqli)) {
http_response_code(500);
die("Falha ao conectar com o banco de dados: " . mysqli_connect_error());
}
If the connection fails, the execution is stopped, displaying the error message on the screen. If all happens successfully, the execution continues.
Note: the function is used http_response_code
to define the code of the HTTP response that the server must deliver to the client, since there was an error in the connection, it is necessary to inform the client that the request he made failed.
3.2) Entering the data into the database
The SQL command to be executed here will depend on the table structure in the database. Given the question that columns exist: id
, titulo
, conteudo
and data_publicacao
I will make the following considerations:
- Column
id
is the type int
, defined as primary key and auto increment;
- Column
titulo
is the type varchar(255)
, nonzero;
- Column
conteudo
is the type text
, nonzero;
- Column
data_publicacao
is the type timestamp
, defined as standard value CURRENT_TIMESTAMP
;
In this way, the values of id
and data_publicacao
will be automatically defined by the database, leaving us only to worry about titulo
and conteudo
(exactly the values we receive via POST).
This way, we can prepare the SQL command to be executed:
if ($stmt = mysqli_prepare($mysqli, "INSERT INTO `publicacoes`(`titulo`, `conteudo`) VALUES (?, ?)")) {
} else {
http_response_code(500);
die("Falha ao preparar o comando SQL: " . mysqli_error($mysqli));
}
To properly replace the characters ?
by their respective values, we use mysqli_stmt_bind_param
:
if ($stmt = mysqli_prepare($mysqli, "INSERT INTO `publicacoes` VALUES (?, ?)")) {
mysqli_stmt_bind_param($stmt, 'ss', $_POST['titulo'], $_POST['conteudo']);
} else {
http_response_code(500);
die("Falha ao preparar o comando SQL: " . mysqli_error($mysqli));
}
Finally, we execute the command with mysqli_stmt_execute
:
if ($stmt = mysqli_prepare($mysqli, "INSERT INTO `publicacoes` VALUES (?, ?)")) {
mysqli_stmt_bind_param($stmt, 's', $_POST['titulo']);
mysqli_stmt_bind_param($stmt, 's', $_POST['conteudo']);
if (mysqli_stmt_execute($stmt)) {
http_response_code(200);
echo "Cadastro realizado com sucesso.";
} else {
http_response_code(500);
echo "Ooops! Algo de errado não está certo: " . mysqli_stmt_error($stmt);
}
} else {
http_response_code(500);
echo "Falha ao preparar o comando SQL: " . mysqli_error($mysqli);
}
Recommended reading:
A possible PHP code to handle, then, this registration, would be:
<?php
// Código padrão da resposta HTTP:
$httpResponseCode = 200;
// Mensagem padrão a ser exibida na tela:
$message = "Yaaay! Seu cadastro realizado com sucesso xD";
// Verifica se o método da requisição é POST:
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_POST["titulo"] && !empty($_POST["conteudo"]))) {
// É POST, então tenta conectar com o banco de dados:
$mysqli = mysqli_connect("localhost", "root", "", "sopt");
// Verifica se a conexão foi realizada com sucesso:
if (mysqli_connect_errno($mysqli)) {
// Não, então emite a resposta HTTP 500 Internal Server Error:
$httpResponseCode = 500;
$message = "Falha ao conectar com o banco de dados: " . mysqli_connect_error();
} else {
// A conexão foi estabelecida, então prepara o comando SQL, verificando se ocorreu erro:
if ($stmt = mysqli_prepare($mysqli, "INSERT INTO `publicacoes`(`titulo`, `conteudo`) VALUES (?, ?)")) {
// Sem erros, então substitui os valores dos parâmetros no comando SQL:
mysqli_stmt_bind_param($stmt, 'ss', $_POST['titulo'], $_POST['conteudo']);
// Executa o comando e verifica se ocorreu erro:
if (!mysqli_stmt_execute($stmt)) {
// Ocorreu algum erro, então emite a resposta HTTP 500 Internal Server Error:
$httpResponseCode = 500;
$message = "Ooops! Algo de errado não está certo: " . mysqli_stmt_error($stmt);
}
} else {
// O comando preparado parece estar errado, então emite a resposta HTTP 500 Internal Server Error:
$httpResponseCode = 500;
$message = "Falha ao preparar o comando SQL: " . mysqli_error($mysqli);
}
}
} else {
// Não é POST, então emite a resposta HTTP 405 Method Not Allowed:
$httpResponseCode = 405;
$message = "Ooops! Eu só aceito o método POST e não gosto de valores vazios.";
}
// Diz ao Apache qual será o código HTTP da resposta:
http_response_code($httpResponseCode);
// Exibe a mensagem na tela:
echo $message;
I don’t know if I can post links but there is this tutorial on youtube that explains very well how to make https://www.youtube.com/watch?v=etRFu_eJ3vU
– user83428