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();

12
  • 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. Commented Jan 10, 2016 at 18:06
  • Use fetchAll(); and change while by foreach with that array ar $results Commented Jan 10, 2016 at 18:10
  • @splash58 I read somewhere fetchAll() consumes a lot of memory.. So I'm worry to use it. Commented Jan 10, 2016 at 18:20
  • Why do you need it there? Commented Jan 10, 2016 at 18:21
  • 1
    If you are going to read everything with fetch anyway, then there is little difference in terms of memory usage. Commented Jan 10, 2016 at 19:01

1 Answer 1

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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, what's your opinion about this: How can I fetch just one column of the result of a query?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.