mysql编写语句,这可能吗?

时间:2010-12-18 17:56:04

标签: php mysql prepared-statement

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;
    }

我可以使用占位符来表名,还是只能用于表格列?

2 个答案:

答案 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);