Search in a field a specific data of the database?

2

I try to select a specific data in a field of the database, in this case I have a field that is called idDepto and it has stored the values 3,4,5,6,7,8 but when executing the query:

$sql = "SELECT Correo, idDepto, Notificacion
        FROM notificaciones
        WHERE FIND_IN_SET =  " . $_POST['id_depto'] . ",idDepto";

At the time of executing the previous query no results appear, and well I decided to use find_in_set because I work well in MySQL, this query is executed in MySQL and if you throw me the results.

  SELECT 'Correo', 'idDepto', 'Notificacion' 
  FROM 'notificaciones' 
  WHERE FIND_IN_SET(5, idDepto) 
    
asked by Jonathan 10.08.2017 в 15:47
source

1 answer

5

Quick Solution

Change your query to the following:

$sql = "SELECT Correo, idDepto, Notificacion
        FROM notificaciones
        WHERE FIND_IN_SET(" . $_POST['id_depto'] . ", idDepto)";

According to what you tell us, the function FIND_IN_SET of MySQL, need to use () , leaving it as follows:

FIND_IN_SET()

But in the example that you pose, it is remaining as follows:

WHERE FIND_IN_SET =  5,idDepto

Therefore, just delete the = and add the parentheses in the query.

Example Try It Here!

Note

  

As a suggestion, and for security measures in your code, it is recommended not to access the POST and GET variables directly . Otherwise it is better to use the filter_input () function.

What would leave your code as follows:

<?php

    $id_depto = filter_input(INPUT_POST, "id_depto", FILTER_SANITIZE_STRING);

    $sql = "SELECT Correo, idDepto, Notificacion
            FROM notificaciones
            WHERE FIND_IN_SET(" . $id_depto . ", idDepto)";

?>

Although there are better practices , such as prepared queries (prepared statements) , this one that I suggest can help you protect a bit of what corresponds to SQL Injection or of unwanted characters. Since this one is in charge of filtering the characters that arrive so much by POST as by GET .

    
answered by 10.08.2017 / 16:00
source