简体   繁体   English

在mysqli提取循环中无法调用函数

[英]Can not call a function while in a mysqli fetch loop

This code just does not work. 此代码不起作用。

$queryProduct = $mysqli->prepare("SELECT productID FROM products WHERE productCat=?");
$queryProduct->bind_param('i', $id);
$queryProduct->execute();
$queryProduct->bind_result($productID);
while ($queryProduct->fetch()) 
{
smallBlockProduct($productID);
}
$queryProduct->close();

This gives me the error "Fatal error: Call to a member function fetch_assoc() on a non-object in" on the line that calls smallBlockProduct. 这在调用smallBlockProduct的行上给了我错误“致命错误:在非对象中调用成员函数fetch_assoc()”。

How ever, if i change the function smallBlockProduct to a simple echo $productID; 但是,如果我将功能smallBlockProduct更改为简单的echo $ productID; it will loop through all the correct results. 它将遍历所有正确的结果。

Can I not call a function in a mysqli fetch loop? 我不能在mysqli提取循环中调用函数吗? Or is there a special way to call a function? 还是有一种特殊的方法来调用函数?

EDIT: 编辑:

The error is actually on the function I am calling. 错误实际上在我正在调用的函数上。 The function exectues another query. 该函数执行另一个查询。

function smallBlockProduct($productID)
   {    
    global $mysqli;

    $query = "SELECT productName FROM products WHERE productID='$productID'";
    $result = $mysqli->query($query);
    while ($row = $result->fetch_assoc())
        {
        $productName = $row['productName'];
        echo $productName.'<br>';
        }
    }

So now, can I not perform a different query while already in another query? 所以现在,我是否可以在另一个查询中执行另一个查询?

It looks like you're trying to call ->fetch_assoc() on $productID that you're passing in to the smallBlockProduct() function. 似乎您要在传递给smallBlockProduct()函数的$productID上调用->fetch_assoc()

I'd suggest checking what $productID is in the function.. 我建议检查一下$productID在函数中。

function smallBlockProduct($productID){
    var_dump($productID);
...

In response to this: So now, can I not perform a different query while already in another query? 对此的回应: 现在,我是否可以在已经处于另一个查询中时执行另一个查询?

You cannot use the same Database connection to execute a second query without losing the first. 您不能使用同一数据库连接来执行第二个查询,而不会丢失第一个查询。 To run a second query you would need to open another connection. 要运行第二个查询,您将需要打开另一个连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM