0

I am trying to upgrade my way to fetch data from sql from mysqli_query to fetchall.

$res = mysqli_query($db, "SELECT * FROM forum_index WHERE forum_over='yes'");
        while ($arr = mysqli_fetch_assoc($res)) {
        ......
    }

So when I use fetchAll() I'll get an array, Am I supposed to use foreach() then or is there a smarter way of doing this?

And to collect a single value from the DB this is the right way right?

$fid = (int)$_GET['id'];
$thread = $db->query("SELECT * FROM forum_threads WHERE f_id=".$fid)->fetch_array();
    echo $thread['id'];
3
  • 1
    Why do you think you need to switch to fetchAll when you switch to PDO? it has fetch(PDO::FETCH_ASSOC), which allows you to keep the same structure. Commented Jan 27, 2018 at 0:06
  • So how would you convert: $res = mysqli_query($db, "SELECT * FROM forum_index WHERE forum_over='yes'"); while ($arr = mysqli_fetch_assoc($res)) { ...... } ? Sorry, trying to get my head around it :) Commented Jan 27, 2018 at 0:11
  • I already answered below. Commented Jan 27, 2018 at 0:12

1 Answer 1

2

You don't need to use fetchAll() just because you're using PDO. If the query returns a large amount of data, this could slow things down because it has to collect it all into memory. You can use the same kind of loop as in your mysqli code:

$res = $pdo->query("SELECT * FROM forum_index WHERE forum_over='yes'");
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
    ...
}

As to your second question, you should use a parametrized query, not substitute variables.

$stmt = $pdo->prepare("SELECT * FROM forum_threads WHERE f_id= :id");
$stmt->bindParam(':id', $_GET['id']);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Now I see how its works, thank you for your explanation Barmar. I need to read some more about pdo, but you solved my current problem. Thanks!

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.