0

For some reason my array I am returning is not what I expect. Could someone explain to me why I am getting the current results, and what I can do to fix it? Here is the code in question:

public static function getProduct($_row, $_value)
{
  $stmt = _DB::init()->prepare("SELECT pid, name, quantity, price, cost 
                                FROM products
                                WHERE $_row = ?"
                              );                            
  if($stmt->execute(array($_value))) 
  {
    while ($row = $stmt->fetch()) 
      return $row;
  }          
}

  $product = Class::getProduct('pid',1);
  print_r($product);

When I print the following array I am getting two results per row like so:

Array ( [pid] => 1 [0] => 1 [name] => Boondoggle [1] => Boondoggle [quantity] => 12 [2] => 12 [price] => 9.9900 [3] => 9.9900 [cost] => 12.9900 [4] => 12.9900 ) Boondoggle

I was only wanting to show the associative results. What is wrong with my function?

1
  • What interface do you use to connect to DB? Commented Jun 12, 2011 at 5:30

2 Answers 2

1

From the looks of it you are using PDO to communicate with your DBMS. The PDOStatement::fetch() method's first argument is a parameter to tell it what to return. By default it returns each column in both name format and numbered index format to allow iterating through columns easier. To just get the column names as indexes, you can pass it PDO::FETCH_ASSOC to your call. So the fetch statement would look like this:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)

See here for more details: http://www.php.net/manual/en/pdostatement.fetch.php

Sign up to request clarification or add additional context in comments.

Comments

1

Pass PDO::FETCH_ASSOC to your fetch call:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) 

edit: I'm just assuming you're using PDO, of course

Comments

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.