How to write values to the Mysql database using PHP?

Asked

Viewed 4,728 times

16

I have a database that I created in MYSQL with the table called publicacoes. This table has the fields id, titulo, conteudo and data_publicacao. I would like to know how to insert values in this table using PHP.

I already have a form that contains the fields titulo and conteudo, but how would I register them in my table?

<!DOCTYPE html>
<html lang="pt-br">
<head>
  <meta charset="utf-8">
  <title>Bootstrap Example</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>nova publicação</h2>
  <form action="/action_page.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>
</div>

</body>
</html>

My database is named after blog, but how to connect PHP to the database?

I’ve heard you have to wear PDO or PHP’s Mysql functions, but could give me a small example?

Note: I realized that there are many users who do not know how to do this initially and also could not find any question in this sense on the site, so I took the initiative to do it.

  • 3

    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

4 answers

18


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:

  1. Who is client and who is server?
  2. What is HTTP?
    • Building the HTTP request with the form
    • Apache and the HTTP request
  3. 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:

  1. host: database server name;
  2. username: bank access user name;
  3. password: bank access user password;
  4. 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:

  1. Column id is the type int, defined as primary key and auto increment;
  2. Column titulo is the type varchar(255), nonzero;
  3. Column conteudo is the type text, nonzero;
  4. 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;
  • 3

    Face, sensational. It’s always interesting to have big answers in contrast to smaller ones. I think it turns out to be beneficial in every way

8

Current libs to connect to Mysql are PDO and Mysqli.

Mysqli allows two types of object-oriented and function-based manipulation (such as the old and obsolete mysql_*).

1 - Create the connection

The first step is to create connection this is done with the function mysqli_connect() it is necessary to inform three arguments, the first is the server, followed by the user, password and optionally the fourth is the name of the database.

$conexao = mysqli_connect('localhost', 'usuario', 'senha', 'nome_do_banco');

Another way would be to call mysqli_select_db() after the connection, it is responsible for selecting or exchanging the database associated with the connection.

$conexao = mysqli_connect('localhost', 'usuario', 'senha');
mysqli_select_db($conexao, 'banco_novo');

2 - Send a query to the bank

Always remember to sanitize the entries sent by the user before sending a query to the bank. There are two ways to do this one by escaping the entrances with mysqli_real_escape_string() and the other with Prepared statements.

2.1

//código da conexão
$sql = sprintf("INSERT INTO publicacoes (titulo, conteudo, data_publicacao) VALUES('%s', '%s', now())", mysqli_real_escape_string($conexao, $_POST['titulo']), mysqli_real_escape_string($conexao, $_POST['conteudo']));
if(!mysqli_query($conexao, $sql)){
   echo 'erro: '. mysqli_error($conexao);
}else{
   echo 'sucesso, linhas incluidas/afetadas: '. mysqli_affected_rows($conexao);
}

This code escapes user inputs ($_POST) with mysqli_real_escape_string() and assigns values in $sql. mysqli_query() is responsible for executing the sent query and always return a flagged Boolean if the operation occurred successfully or not.

When an error happens get the error message that the bank sent with the function mysqli_error().

For DML (Insert, update and delete) it is sometimes interesting to know how many lines were included/modified/removed in the block else the function mysqli_affected_rows() provides this information, in this example the result will always be a.

2.2

Some advantages of using Prepared statments are:

  • The fact of sending the query and the values in a seperate way.

  • Better organization of the query by the absence of simple quotes in the values.

  • Queries that are often executed take advantage of being 'compiled' by the database, basically the same statement is executed N times and what will change are the values.

For DML it is necessary two steps to define the query and then bind (link) that the indication of which value an argument/score Holder (the query) will assume.

//código da conexão
$stmt = mysqli_prepare($conexao, "INSERT INTO publicacoes (titulo, conteudo, data_publicacao) VALUES(?, ?, now()");
mysqli_stmt_bind_param($stmt, 'ss', $_POST['titulo'], $_POST['conteudo']);
if(!mysqli_stmt_execute($stmt)){
    echo 'erro: '. mysqli_stmt_error($conexao); 
}
  • The order of the columns with their values does not matter?

  • @Leocaracciolo is based on position, the first interrogation will assume the value of $_POST['titulo'] and so it goes.

  • I refer to item 2.1

  • @Leocaracciolo is also based on position.

4

You need a connection to the database:

php connection.

<?php
$servidor = 'localhost';//Teu servidor
$usuario = 'root';//Teu usuário do Mysql
$senha = '';//Tua senha se houver
$banco = 'blog';//Teu banco
$con = new mysqli($servidor, $usuario, $senha, $banco);//A conexão
if($con->connect_error)
{   die("Connection failed: ".$con->connect_error);//Se teve erro mostra
} 
?>

Now you need to take the form information and enter it in the database:

action_page.php

<?php
include 'conexao.php';//Inclui a conexao

$titulo = $_POST['titulo'];//Atribui o valor do campo com o name titulo a variavel
$conteudo = $_POST['conteudo'];//Atribui o valor do campo com o name conteudo a variavel

$sql = "INSERT INTO publicacoes (titulo,conteudo,data_publicacao) VALUES ('$titulo','$conteudo',NOW( ))";//Monta a query para inserção no bd
$con->query($sql);//Executa a query
?>

4

First of all, fix your HTML because the way your form is will not insert the data into your database table. Enter the method Example: <form action="/action_page.php" method="post">

Configure the column data_publicacao for the TIMESTAMP type in your database table and put in the Default CURRENT_TIMESTAMP value.

We define in the column data_publicacao A DEFAULT CURRENT_TIMESTAMP for when we receive a NULL value, the DBMS itself will enter the current date/time in this field.

Detail, each value of this column will consume only 4 bytes, while if we had the type DATETIME, it would consume 8 bytes.

PHP

//Abre uma conexão com um servidor MySQL
$conn = new mysqli ("localhost", "USUARIO", "SENHA", "blog");

//Recupera os valores enviados do formulario
$titulo = $_POST['titulo'];
$conteudo = $_POST['conteudo'];

//insere dados no banco
$squery = "INSERT INTO publicacoes (titulo, conteudo) VALUES('$titulo','$conteudo')";
$resultado = mysqli_query($conn,$squery);


if($resultado === false){
   // Caso algo tenha dado errado, exibe uma mensagem de erro   
   echo 'erro: '. mysqli_error($conn);
}else{
   // Aviso de registro criado com sucesso
   echo 'Operação realizada com sucesso';
}

//fecha conexão
mysqli_close($conn);

I think this way is easier for those who are starting.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.