PHP - Delete values of a variable $ _POST with str_replace

2

Good day. I would like to delete some values of a query that I receive via POST. I have a variable $ query which receives the value = SELECT * FROM equipos WHERE () AND (( nombre='computadora' OR nombre='mouse' OR nombre='teclado' )) AND (( departamento='Electronica' )) where I want to eliminate the empty AND () AND . Thank you in advance.

Here is my code:

 <?php
 session_start();
 $consulta = $_POST["consulta_sql_general"];

 $and_vacios = array('() AND', ' () AND ', 'AND ()', ' AND () '); // 
 expresiones no admitidas

 $consulta1 = str_replace($and_vacios, '', $consulta);
 echo $consulta;

 ?>
    
asked by Julian Martinez 04.07.2018 в 23:39
source

2 answers

2

str_replace does not work well with arrays the way you try to use it.

You can do the following:

  • First of all, clean the chain of possible blank spaces. You can easily mistakenly write more than one blank space, and if that happens, it would knock out the logic of the program. Also, doing that you no longer have to search: AND () and AND () , with which you search AND () would suffice. However, I have added two possible erroneous values to $replaceAnds , which are AND() and ()AND , since it is a common mistake to forget the spaces of separation, especially when the values are concatenated.
  • Then prepare an array of explicit replacements for each case.

The code would be this:

$consulta = "
                SELECT * FROM equipos WHERE 
                ()  AND (( nombre='computadora' OR nombre='mouse' OR nombre='teclado' )) 
                AND (( departamento='Electronica' ))
                () AND () AND () AND      AND () () AND  ()AND         AND()
             ";

/*Limpiamos la cadena de espacios en blanco sobrantes que podrían darnos muchos problemas*/
$consulta= preg_replace('/\s+/', ' ', $consulta);;

/*Creamos un array de reemplazos explícito*/
$replaceAnds = array(
'() AND' =>  '',
'AND ()'  => '',
'AND()'  => '',
'()AND'  => '',
);

$resultado = str_replace(array_keys($replaceAnds), $replaceAnds, $consulta);
echo $resultado;

You would have as a result:

 SELECT * FROM equipos WHERE (( nombre='computadora' OR nombre='mouse' OR nombre='teclado' )) AND (( departamento='Electronica' ))  
  

Note:

     

It is possible to improve the logic that is producing your   consult, then it should not be created like this. You should implement a   kind of intelligent query builder that knows when to create the AND and   when not.

    
answered by 05.07.2018 / 00:25
source
0

I recommend you use preg_replace which allows you to create a regular expression and replace what meets the regular expression. Something like this:

<?php
 session_start();
 $consulta = $_POST["consulta_sql_general"];

$pattern="/\s*(AND)*\s*\(\s*\)\s*(AND)*/";
$consulta1 = preg_replace($pattern,'',$consulta);

echo $consulta;
 ?>
    
answered by 04.07.2018 в 23:54