PDO array issue

I have the chunk of code below to turn into PDO, have had a go but I keep getting an error.

This is the original

$result = sqlsrv_query($conn, $sql); 
$r = sqlsrv_fetch_array($result);  
$numrows = $r[0];

This is what Im trying but its not working

$r = $conn->prepare($sql);
$r->execute();
while ($rows = $r->fetch(PDO::FETCH_ASSOC)) {
$numrows = $rows[0];
}

and that would be which one?

btw. that whole PDO code makes no sense:

  • if there are no data in the query, there is no need to use a prepared statement
  • PDO works best with foreach(). while() is too cumbersome.
  • depending on what result you want, there is certainly a better matching fetch mode for it.

I would guess

$r = $conn->query($sql);
$numrows = $r->fetchColumn();

would do the job as well.

1 Like

Sorry ye I forgot to post the error, its

Notice: Undefined offset: 0 in

An associative array does not have a numeric index.

I see, so how I retrieve $rows[0]

See post #2

1 Like

ah sorry, so i can call it by using $numrows[0]

why making it more complicated than it actually is?

Right I see, so i dont need to add the array position on it, ok thank you Dormilich

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.