Pass Array to Int - PHP

2

I need to obtain the id of the student with his rout (identification number) which I achieve in the query that I do in PDO the problem in which an array returns and not an int.

Then I was in doubt transform the value obtained in an integer or change the query to get an integer, as I understand always returns an array.

And how can I do it?

Querry

public function alumnos_id($rut){

    try {
        $result = array();
        $sql = "SELECT alu_id FROM alumno WHERE alu_rut='$rut'";
        $stm = $this->pdo->prepare($sql);        
        $stm->execute();

       foreach ($stm->fetchAll(PDO::FETCH_OBJ) as $r) {

            $alm = array(
                            'alu_id' => $r->alu_id
                        );
            $result[] = $alm;
        }   

        return $result;    

        } catch (Exception $e) {
            echo $e;
        }

}

PHP

require_once('funciones/web_services/alumnos_ws.php');
$alumnos_obj = new alumnos_ws();
$alumnos_id = $alumnos_obj->alumnos_id($rut_alumno);

echo $alumnos_id;

This returns to me on the screen a word "Array".

    
asked by Gustavo 07.08.2017 в 19:09
source

1 answer

2

If you only need the student's id, you can use fetchColumn() as I have commented before. It is the right method when we only need one column . Everything you do in foreach in this case, that's why I've commented.

I have modified the code giving it security, so a prepared query is created:

    $sql = "SELECT alu_id FROM alumno WHERE alu_rut =: rut";

And then the value is passed separately:

    $stm->bindValue(":rut",$rut);

That way we avoid SQL injection.

The function would look like this:

public function alumnos_id($rut){

    try {
        /* $result no sería un array
        $result = array();
        */ 
        $sql = "SELECT alu_id FROM alumno WHERE alu_rut =: rut";
        $stm = $this->pdo->prepare($sql);        
        $stm->bindValue(":rut",$rut);
        $stm->execute();
        $result = $stm->fetchColumn();

       /* Si esperas un solo resultado esto sobra ...

       foreach ($stm->fetchAll(PDO::FETCH_OBJ) as $r) {

            $alm = array(
                            'alu_id' => $r->alu_id
                        );
            $result[] = $alm;
        }   

        */     
        return $result;    

        } catch (Exception $e) {
            echo $e;
        }

}
    
answered by 07.08.2017 / 19:34
source