i am writing a customer database. I've got a function to show all customers that looks like this.
<?php
class customer{
public function getAllCustomers(){
global $database;
$query = $database->query('SELECT * FROM hs_customers');
$result = $database->statement->fetchAll();
return $result;
}
}
?>
Until up here everything works well. Its connecting, im getting data and so on. The only thing i am unhappy with is i don't want the database name to be hardcoded inside the function, furthermore i want it to be replaced by a variable. So id did the following (as i did before, and it worked out well) but suddenly it wont replace the variable anymore?...
<?php
class customer{
private $customerDB = 'hs_customers';
public function getAllCustomers(){
global $database;
$query = $database->query('SELECT * FROM :db', array(':db' => $customerDB));
$result = $database->statement->fetchAll();
return $result;
}
}
?>
I guess i've got something wrong. Any advice? Thank you in advance.
You cannot use variable containers on syntax that is used by SQL, e.g. a table name
or anything else related to the syntax like order
, group
etc. So in order to dynamically do this you have to escape the SQL string and use it like
$query = $database->query('SELECT * FROM '.($this->customerDB));
-- update for @TimG
And because you are in a class environment, the variable $customerDB
should be treated as a class property. You have to use $this->
assignment to use any property of a class, unless it is static in that case, use self::
.