不能使用 PDO ->bindParam() 绑定表和列名称,但我相信不止一个人愿意这样做。有点晚了,但我早点写了这个,到目前为止它有效。我是 php 的新手,想知道您的想法以及它是否安全。
$type = "defaultTableName";
$sortBy = "defaultColumnName";
$orderBy = "ASC";
//whitelisting unsafe input
if(isset($_GET['orderBy'])&&($_GET['orderBy']=="ASC"||$_GET['orderBy']=="DESC"))
$orderBy = $_GET['orderBy'];
$tableNames = array("defaultTableName", "tableName2", "tableName3");
$unsafeType= $_GET['type']; <---unsafe input
$unsafeSortBy = $_GET['sortBy']; <---unsafe input
try {
$pdo = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//if input is not valid this will use default table to render a table in html.
$stmt = $pdo->prepare("DESCRIBE $type");
$stmt->execute();
$table_fields = $stmt->fetchAll(PDO::FETCH_COLUMN);
//Whitelisting user input against table names (will require table names updates)
if (in_array($unsafeType, $tableNames)) {
$stmt = $pdo->prepare("DESCRIBE $unsafeType");
$stmt->execute();
$table_fields = $stmt->fetchAll(PDO::FETCH_COLUMN);
///Whitelisting the column name to sort by against the description of the table.
if (in_array($unsafeSortBy, $table_fields)) {
$stmt = $pdo->prepare("SELECT * FROM $unsafeType ORDER BY $unsafeSortBy $orderBy");
}
else {
$stmt = $pdo->prepare("SELECT * FROM $type ORDER BY $sortBy $orderBy");
}
} else {
$stmt = $pdo->prepare("SELECT * FROM $type ORDER BY $sortBy $orderBy");
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
我看到的唯一问题是您在更改表时需要添加/删除/更改表名数组。我有一个中小型应用程序,不是很复杂。
注意:我在 stackoverflow 中的编辑也很糟糕,所以如果你知道一种使它更好的方法,请继续编辑或让我知道。