grep
grep

Reputation: 4016

PHP and PDO issues

I was wondering if there is a way to do the following which does not throw me an error. Would someone be able to explain why the following is not possible, and how I can pull it off?

Here is the function:

public function getTaxClass()
{
  $arg = func_get_args();
  $pid = array_shift($arg); 
  $imp = implode(',',$arg);

  $stmt = _DB::init()->prepare("SELECT $imp
                                FROM tax_class a
                                INNER JOIN products_to_tax_class pa ON a.tid = pa.tid
                                WHERE pa.pid = ?"
                              );
  if($stmt->execute(array($pid))) 
    return $stmt->fetch(PDO::FETCH_ASSOC);

}

Am I unable to insert variable into a prepared statement? I tried building the string before adding it into the prepare however I still get the following warning:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'tid' in field list is ambiguous' in /class.php:89 Stack trace: #0 /class.php(89): PDOStatement->execute() #1 /class.php(98): _Class->getTaxClass(1, 'tid', 'name', 'rate') #2 {main} thrown in/class.php on line 89

Upvotes: 1

Views: 341

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270609

The error states that the column tid is ambiguous, because it is included in both you aliased a table and b table. To clear that up, it needs to appear in the SELECT columns list as either a.tid OR b.tid. By your implode() it's only arriving into the select list as tid.

The simplest way to fix it would be to specify the table and column as table.column to all of your columns when you pass them in as the function arguments.

Or, you could prepend the table like so, before doing the implode():

// Assuming all your columns belong to the `a` table alias...
$arg = func_get_args();
$pid = array_shift($arg); 
$prepared_args = array();

// Loop over your remaining column name arguments and prepend `a.` to each
foreach($arg as $a) {
  $prepared_args = "a.$a"
}

$imp = implode(",", $prepared_args);

// Finish up your PDO stuff...

Upvotes: 2

JoshuaRogers
JoshuaRogers

Reputation: 405

It looks like $imp contains "tid". Since two tables have columns by the name of tid, SQL isn't quite sure which one your want returned. (Even though the two of them should be the same.) Try putting "a.tid" in your $imp.

Upvotes: 2

Related Questions