我可以对 bind_param() 类型中的所有值使用 string ("sss...") 吗?如果没有,为什么不呢?

问题描述

我正在我的类中创建一个方法,该方法的参数是 $sql,$types,$values

function getResult($sql,$values){
    $stmt = $this->conn->prepare($sql);
    $stmt->bind_param( "$types",...$values);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        return $result;
    } else{
        return "There is no such row";
    }
}

但我想知道,也许我可以创建一个函数,其中根据 $types 的计数自动生成 $values 并给它一个字符串 ("s")。像这样:

function getResult($sql,$values){
    $stmt = $this->conn->prepare($sql);
    $types = str_repeat("s",count($values));
    $stmt->bind_param( $types,...$values);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        return $result;
    } else{
        return "There is no such row";
    }
}

这是不好的做法吗?它会使代码更小

解决方法

是的,您绝对可以使用字符串来绑定每个参数。将参数绑定为字符串的概率为 99.99%。在 MySQL 中,参数类型很重要的情况很少。

您可以做的是创建一个将 $types 作为可选参数的函数。这将是最佳实践,因为如果您确实需要它们,您可以选择指定类型。

function getResult(string $sql,array $values,?string $types = null): ?mysqli_result
{
    $stmt = $this->conn->prepare($sql);
    if (is_null($types)) {
        $types = str_repeat("s",count($values));
    }
    $stmt->bind_param($types,...$values);
    $stmt->execute();
    return  $stmt->get_result() ?: null;
}

附言让函数返回两种类型的值是一个坏主意。类型提示您的功能并坚持使用单一类型。