php – mysqli使用fetch_assoc准备语句

我的目标是能够获得一个变量(使用php)并在准备好的语句中使用它(使用mysqli),然后使用fetch_assoc.由于某种原因,此代码不起作用(没有错误).我rtm并没有找到任何将fetch_assoc与预处理语句相结合的东西,所以我不确定它是否可能.任何有助于实现这一目标的帮助表示赞赏,这是我目前的代码.

$where = $_GET['section'];
            $mysqli = mysqli_connect("localhost", "root", "","test");

            if($stmt = mysqli_prepare($mysqli,"SELECT title, img, active, price FROM ? ORDER by ID limit 5 ")){
                mysqli_stmt_bind_param($stmt, 's', $where);
                mysqli_stmt_execute($mysqli);
                mysqli_stmt_fetch($mysqli);
                 while($row = mysqli_fetch_assoc($stmt)){
                    if($row['active']=="yes"){
                        echo 'the rest of my stuff goes here';
最佳答案
从PHP网站页面mysqli->prepare(重点添加到最相关的部分):

Note:

The markers are legal only in certain places in SQL statements. For
example, they are allowed in the VALUES() list of an INSERT statement
(to specify column values for a row), or in a comparison with a column
in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column
names)
, in the select list that names the columns to be returned by a
SELECT statement), or to specify both operands of a binary operator
such as the = equal sign. The latter restriction is necessary because
it would be impossible to determine the parameter type. In general,
parameters are legal only in Data Manipulation Language (DML)
statements, and not in Data Definition Language (DDL) statements.

假设你可以解决这个问题,你对mysqli的使用有点困惑.您正确绑定了参数并执行,但您已经混淆了两种不同的方法来获得结果.或

>使用mysqli_stmt_get_result获取结果集,然后在其上使用mysqli_fetch_assoc,或者
>使用mysqli_stmt_bind_result绑定结果,然后使用mysqli_stmt_fetch将下一组结果提取到绑定变量中. (通常你会使用像while这样的东西迭代结果(mysqli_stmt_fetch($stmt)){//在这里做东西}

转载注明原文:php – mysqli使用fetch_assoc准备语句 - 代码日志