Class only deletes a record with IN clause (Array)

0

From a shipping form $_POST['seleccion'] that is a list of codes, the amount varies depending on whether it is selected in the form. In the controller I separate the codes and invoke the class:

$eliminar = implode(',', $_POST['seleccion']);
$eliminaAlumno = new Alumnos();
$OK = $eliminaAlumno->eliminar($eliminar);

The class is the following:

public function eliminar($lista) {
    $bd = new Conn();
    $IN = str_repeat('?,', count($lista) - 1) . '?';
    $sql = "DELETE FROM tabla WHERE cod IN ($IN)";
    $sth = $bd->prepare($sql);
    $sth->bindParam(1, $lista, PDO::PARAM_INT);
    $sth->execute();
}

I used as a basis this question I added < em> bindParam to verify that all codes are Integer . The problem is that it only deletes one record and not all the codes it receives. What is the problem?

    
asked by Piropeator 11.12.2018 в 22:54
source

1 answer

1

The problem is that PARAM_INT converts to an integer so it only takes the first id you pass, to avoid this you must set it as PARAM_STR since what you are going through is a String not an integer, it is say, the bindParam() should look like this:

$sth->bindParam(1, $lista, PDO::PARAM_STR);

You can check the predefined PDO Constants here: link

You should keep in mind that a list of integers is different from a whole number:

Example:

echo (int) '1,2,3,4,5';  // 1

echo (int) 1;  // 1

echo (string) '1,2,3,4,5'; // 1,2,3,4,5
    
answered by 11.12.2018 / 23:43
source