bentham
bentham

Reputation: 1717

Problem with a while loop

My query does no return anything for my second index. It always sends me a message Notice: Undefined offset: 1. I tried doing with a for it is the same result, so I have read that my problem it is in the query, somebody told me let $stmt be null for freeing resources of my statement. I dont know what is wrong.

These are my methods. I dont know what to someone say use $database->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);

Example: $arrayDirectory[] = {'user1', 'user2'};

It must echo 1 2 but just prints me 1

for($i=0;$i<sizeof($arrayDirectory;$i++){ 
    $res[$i] = $obj->obtainID($arrayDirectory[$i]);

    echo $res[$i];
}

This is my obtainID method:

public function obtainID($user){
        $conexion = $this->objConexion->configuracion();
        $query = "CALL sp_xxx('$user')";
        $stmt = $conexion->prepare($query);
        $stmt->execute();
        $resultado = $stmt->fetchColumn();
        return $resultado;
    }

$stmi = null where?

Upvotes: 0

Views: 110

Answers (2)

SAFAD
SAFAD

Reputation: 784

first of all you are wrong with your function, you forgot to add the ending ')' for sizeof function,also arrays aren't defined with { } you should use array( ) instead.

and finally you are doing a bad practice over there; you should not call a function in a loop (sizeof()), like this every time the loop goes through it will initiate sizeof() function and it will take some resource, since sizeof($object) won't change while using the loop, you should save it in a variable

$sizeofobject = sizeof($object);

and use that variable in your loop instead

Upvotes: 0

Marc B
Marc B

Reputation: 360922

For one,

 $arrayDirectory[] = {'user1', 'user2'};

is a syntax error. { ... } does not work for arrays in PHP. Maybe it's just a typo and you're getting PHP confused with javascsript.

But the bigger issue is the []. That tells PHP to treat $arrayDirectory as an array (fine), but PUSH as a single value whatever you're assigning.

If your code was really:

$arrayDirectory[] = array('user1', 'user2');

This would create the following structure:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "user1"
    [1]=>
    string(5) "user2"
  }
}

Note that it's a 2-level array. A top level single-element array at index [0]. That element at 0 contains ANOTHER array, which contains your two usernames.

You should have this instead:

$arrayDirectory = array('user1', 'user2');

$res = array();
foreach($arrayDirectory as $user) {
    $res[] = $obj->obtainID($user);
}

Upvotes: 4

Related Questions