I've got a function written that runs a query based on parameters passed to the function.
I can't seem to figure out why doing the following returns a result:
function test($function_returned_array)
{
$variable = 'Hello World';
$sql = 'SELECT `name`, `pid`
FROM `products`
WHERE `name` IN (?)';
$found = $this->db->get_array($sql, $variable);
}
While this doesn't return any results:
function test2($function_returned_array)
{
$sql = 'SELECT `name`, `pid`
FROM `products`
WHERE `name` IN (?)';
$found = $this->db->get_array($sql, $function_returned_array[0]);
}
$function_returned_array[0] is also equal to 'Hello World'. Shouldn't they both return the same results?
When I echo the values of $variable and $function_returned_array[0], they are both 'Hello World'
Here's the relevant parts of my PDO wrapper:
public function query(&$query, $params)
{
$sth = $this->_db->prepare($query);
if(is_null($params))
{
$sth->execute();
}
else if(is_array($params))
{
$sth->execute($params);
}
else
{
$sth->execute(array($params));
}
$this->_rows = $sth->rowCount();
$this->_counter++;
return $sth;
}
public function get_array(&$query, $params, $style = PDO::FETCH_ASSOC)
{
$q = $this->query($query, $params);
return $q->fetchAll($style);
}
I'm using PHP 5.3.5.
Any help would be appreciated.
i have witnessed the same problem in PDO. PDO only accepts the local variable for parametrized query and not by reference or argument not sure why though.
the workaround for it can be.
function test2($function_returned_array)
{
$variable = $function_returned_array[0];
$sql = 'SELECT `name`, `pid`
FROM `products`
WHERE `name` IN (?)';
$found = $this->db->get_array($sql, $variable);
}
Update:
You are doing it wrong. you have to Use PDO prepare() statement for parameterized query whereas i see you are using the PDO query() directly into your get_query() method.
you should use query()
method only if you don't want to pass any parameter to the query.and according to php documentation here is the syntax
PDOStatement PDO::query ( string $statement )
the second argument you are trying to pass is wrong.
so instead use prepare()
method, and here is the link.
Just a heads up, the problem was that $function_returned_array[0] and $variable did not really equal the same thing. $function_returned_array[0] needed to be passed through an html_entity_decode().