How to search for 2 fields in PHP?

1

I am trying to perform a search for 2 fields, both are in the same table, I want to look for a data captured in the bd either by the name of the team that is what is captured or by the date when it was captured.

For now I can only search for a single field I can not make it look for any of the 2, or search by name or by date, this is what I have.

This is the function by which I send the values to make the selection.

public function Buscar($campo_buscar, $datos_buscar)
{
    # code...
    $conexion = $this->getConection();

    $rows = array();
    if ($datos_buscar == '') {
        $query = $conexion->prepare("SELECT * from " . $GLOBALS['tabla']);
    } else {
        $query = $conexion->prepare("SELECT * from " . $GLOBALS['tabla'] . " WHERE " . $campo_buscar . " LIKE :b");
        $query->bindValue(':b', '%' . $datos_buscar . '%', PDO::PARAM_STR);
    }

    if (!$query) {
        return "Error al mostrar";
    } else {
        $query->execute();

        while ($result = $query->fetch()) {
            $rows[] = $result;
        }

        return $rows;
    }

    //$conexion->close();
}

And here I put the data that I want to look for, but in this case they are 2 is not one,

    // Buscar
$campo_buscar =  NombreEquipobd;
$datos_buscar= $_POST['txtBuscar'];


//Buscar
$campo_buscarfecha =  fechadeta;
$datos_buscartxtf = $_POST['txtfecha'];
    
asked by Jonathan 08.08.2017 в 19:10
source

3 answers

1

Hello you must place an AND to your sentence:

$query = $conexion->prepare("SELECT * from " . $GLOBALS['tabla'] . " WHERE " . $campo_buscar . " LIKE :b AND ".$datos_buscar." = '".$datos_buscartxtf."'");
    
answered by 08.08.2017 / 19:16
source
1

should you simplify more can you remove line from bindValue why? It is simple because you are searching with a text field that is of type String and then you want to perform a search with txt date that is of type INT therefore the restriction that you give PDO :: PARAM_STR would not give you good results, therefore write directly.

$query = $conexion->prepare("SELECT * from ".$GLOBALS['tabla']." WHERE " . $campo_buscar." LIKE '%$datos_buscar%'");
    
answered by 08.08.2017 в 20:04
1

Use UNION to search several values in the same field of the table

ejem

$sql = '';
$count = 0;
foreach($search as $text)
{
  if($count > 0)
     $sql = $sql."UNION Select name From myTable WHERE Name LIKE '%$text%'";
  else
     $sql = $sql."Select name From myTable WHERE Name LIKE '%$text%'";

  $count++;
}
    
answered by 09.08.2017 в 00:37