3

What is the equivalent of these two code in PDO

first:

  $row=mysql_fetch_array($query);

second:

 while($row=mysql_fetch_array($query)){
   $data[]=$row;
 }

i used these codes below but they are not exact same i guess, because the rest of the code didn't work.

$row = $query->fetch(PDO::FETCH_NUM);

and

 $data[] = $query->fetch(PDO::FETCH_ASSOC);

2 Answers 2

16

Here are the correspondences:

  • mysql_fetch_array = fetch(PDO::FETCH_BOTH) - The rows are arrays with both numeric and named indexes.
  • mysql_fetch_assoc = fetch(PDO::FETCH_ASSOC) - The rows are arrays with named indexes.
  • mysql_fetch_row = fetch(PDO::FETCH_NUM) - The rows are arrays with numeric indexes.
  • mysql_fetch_object = fetch(PDO::FETCH_OBJ) or fetch(PDO::FETCH_CLASS) depending on whether you specify the optional className argument to mysql_fetch_object. The rows are objects, either of the specified class or stdClass.

The while loop is equivalent to:

$data = $query->fetchAll(PDO::FETCH_BOTH)
Sign up to request clarification or add additional context in comments.

Comments

0

You should be able to get the data of the query in an array with this:

$data = $query->fetch(PDO::FETCH_BOTH);

If that's not working, your PDO connection is probably not setup right or your query didn't run. You can try troubleshooting the query with something like this:

try {
    $query->execute();
} catch (PDOException $e) {
    echo 'Query failed: ' . $e->getMessage();
}

4 Comments

thank you for your answer. this code is valid i know. However, i am looking for a script that, when i changed with old code works same. because the rest of the code is really long and if i change alot, i will have to change all
So you're confident that the query is executing fine?
@RubyMewMew It should be PDO::FETCH_BOTH to match the original code.
Sidenote: During development (only), it's better to use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); right after the connection is opened. Doing just a catch(PDOException $e) isn't always enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.