function fetchbyId($tableName,$idName,$id){
global $connection;
$stmt = mysqli_prepare($connection, 'SELECT * FROM ? WHERE ? = ?');
var_dump($stmt);
mysqli_stmt_bind_param($stmt,'s',$tableName);
mysqli_stmt_bind_param($stmt,'s',$idName);
mysqli_stmt_bind_param($stmt,'i',$id);
$stmt = mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($name,$id);
$fetchArray = array();
while($row = mysqli_stmt_fetch($stmt)){
$fetchArray[] = $row;
}
return $fetchArray;
}
我可以使用占位符来表名,还是只能用于表格列?
答案 0 :(得分:1)
表/列名称可以安全地直接插入到字符串中,因为它们来自经过验证的有限的一组有效表/列名称(对吗?)。只有用户提供的值才是参数。
function fetchbyId($tableName,$idName,$id){
global $connection;
$stmt = mysqli_prepare($connection, "SELECT * FROM $tableName WHERE $idName = ?");
mysqli_stmt_bind_param($stmt,'i',$id);
$stmt = mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($name,$id);
$fetchArray = array();
while($row = mysqli_stmt_fetch($stmt)){
$fetchArray[] = $row;
}
return $fetchArray;
}
答案 1 :(得分:1)
不,它只接受值(即:不是列,表名,模式名称和保留字),因为它们将被转义。你可以这样做:
$sql = sprintf('SELECT * FROM %s WHERE %s = ?', $tableName, $idName);
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt,'i',$id);