I have a class with a function that will pull out any data from the database whatever the identifying column may be, which basicly looks like this
use Database\DB;
class General extends DB
{
private $fooBar;
public function getData($column, $table, $value) {
$column = (array) $column;
$column = implode(', ', $column);
$test = $this->query("SELECT `$column` FROM `$table` WHERE $column[0] = :value", array("value" => $value));
}
}
and is executed as following:
return $this->general->getData(['name'], 'people', 'John Anderson');
However, I'm getting an error which tells me there is an non-existent column input with the value 'n' (which is happening to be the first character of the column name, whatever the column name's value is)
Full error;
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'n' in 'where clause'' in a\long\path\DB.class.php on line 50
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'n' in 'where clause' in a\long\path\DB.class.php on line 50
Thanks in advance, Jordi
Get rid of the line
$column = implode(', ', $column);
It's replacing the array with a string containing all the column names separated by comma. Then $column[0]
will be the first character of the first column name, instead of the first column name.
Put down your full query here.. Than it's easier!
Edit:
try this code:
use Database\DB;
class General extends DB
{
private $fooBar;
public function getData($column, $table, $value) {
$columns = (array) $column;
$column = implode(', ', $columns);
$test = $this->query("SELECT `$column` FROM `$table` WHERE $columns[0] = :value", array("value" => $value));
}
}
I changed the following: $column = (array) $column;
to $columns = (array) $column;
And
SELECT `$column` FROM `$table` WHERE $column[0] = :value", array("value" => $value)
to
SELECT `$column` FROM `$table` WHERE $columns[0] = :value", array("value" => $value)
This should fix it (see @Barmar answer as well):
(Take note of the difference in the implode statement as well).
use Database\DB;
class General extends DB
{
private $fooBar;
public function getData($column, $table, $value) {
$column = (array) $column;
$whereCol = $column[0];
$column = implode('`, `', $column);
$test = $this->query("SELECT `$column` FROM `$table` WHERE $whereCol = :value", array("value" => $value));
return $test;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.