我想知道是否可以定义表名和列名,并在php脚本中的不同sql查询中使用它们。
我尝试了一些组合:
define("USERS_TABLE", "users");
define("COLUMN_NAME", "username");
function getUserName()
{
$dbh = new DBHandler();
if ($dbh->getInstance() === null) {
die("No database connection");
}
try {
$sql = "SELECT".COLUMN_NAME."FROM".USERS_TABLE"where id=1";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->execute();
return $number_of_rows = $stmt->fetchColumn();
}
}
我也尝试过:
try {
$sql = "SELECT :column FROM :table where id=1";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->bindParam(':column', COLUMN_NAME, PDO::PARAM_STR);
$stmt->bindParam(':table', USERS_TABLE, PDO::PARAM_STR);
$stmt->execute();
return $number_of_rows = $stmt->fetchColumn();
}
和
define("USERS_TABLE", "users");
define("COLUMN_NAME", "username");
$tablename= USERS_TABLE;
$columnname = COLUMN_NAME;
function getUserName() use ($tablename,$columnname)
{
try {
$sql = "SELECT :column FROM :table where id=1";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->bindParam(':column', $columnname, PDO::PARAM_STR);
$stmt->bindParam(':table', $tablename, PDO::PARAM_STR);
$stmt->execute();
return $number_of_rows = $stmt->fetchColumn();
}
}
但没有任何成功。也许不可能做这样的事情?感谢