1

I need the values of one columns before fetching the query. Something like this:

// mytable
+----+-------+
| id | codes |
+----+-------+
| 1  | 102   |
| 2  | 64    |
| 3  | 563   |
| 4  | 79    |
+----+-------+

My query:

$db = new PDO("mysql:host=localhost;dbname=mydb", "root", "");
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sth = $db->prepare("SELECT * FROM mytable");
$sth->execute();

/* I need to those numbers in the codes-column as an array in here */

while ($results = $sth->fetch()) {
    var_dump($results);
}

Well, how can I access this array [0]=>102, [1]=>64, [2]=>563, [3]=>79 before that while() in the above code?

Note: Preferably without the use of fetchAll();

stack
  • 10,280
  • 19
  • 65
  • 117
  • 2
    well, you'll have to fetch them some way... there is no magic clairvoyance by which you can get it without those database functions. So either `fetchAll`, or a second loop based on `fetch`. – trincot Jan 10 '16 at 18:06
  • Use fetchAll(); and change `while` by `foreach` with that array ar `$results` – splash58 Jan 10 '16 at 18:10
  • @splash58 I read somewhere `fetchAll()` consumes a lot of memory.. So I'm worry to use it. – stack Jan 10 '16 at 18:20
  • Why do you need it there? – Alex Blex Jan 10 '16 at 18:21
  • @AlexBlex In reality those numbers are `post_id` and I need those numbers to use them in another query to fetch all comments and then paste comments under its own post. – stack Jan 10 '16 at 18:23
  • i think you can do this in mysql query – splash58 Jan 10 '16 at 18:28
  • Fair enough, but I fail to see what stops you to collect these codes into array within the `while` loop. btw, you may be able to fetch both posts and comments in a single query. – Alex Blex Jan 10 '16 at 18:30
  • Ok I will try it. Thanks guys – stack Jan 10 '16 at 18:31
  • @trincot You said: *"or a second loop based on `fetch`"*. Well how can I fetch a query twice? – stack Jan 10 '16 at 18:37
  • See http://stackoverflow.com/questions/9437214/resetting-array-pointer-in-pdo-results – trincot Jan 10 '16 at 18:47
  • @trincot Thanks *(I'd seen it before, though)* , that is `fetchAll()` ;-), I thought there is another way except `fetchAll`.. To be honest, I afraid to use `fatchAll`. I scare my memory get full quickly. – stack Jan 10 '16 at 18:51
  • 1
    If you are going to read everything with fetch anyway, then there is little difference in terms of memory usage. – trincot Jan 10 '16 at 19:01

1 Answers1

0

Your question is like saying How can I fetch data without fetching it ?

This is obviously impossible, you will need to fetch it at some point in your application.


if($results = $sth->fetch()) {
    var_dump($results);
}
meda
  • 45,103
  • 14
  • 92
  • 122
  • Ok, what's your opinion about this: How can I fetch just one column of the result of a query? – stack Jan 10 '16 at 19:17