0

我有以下代码:

/* Get the 10 latest posts from users you're following */
$stmt = $cxn->prepare('SELECT * FROM posts WHERE user_id IN (SELECT following_id FROM follows WHERE user_id = ?) ORDER BY datetime DESC LIMIT 15');
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();

/* If a result exists, continue. */
if ($result->num_rows) {
    while ($row = $result->fetch_assoc()) {

        /* Get the user's username from their id */
        $stmt = $cxn->prepare('SELECT username FROM users WHERE user_id = ?');
        $stmt->bind_param('i', $row['user_id']);
        $stmt->execute();
        $stmt->bind_result($username);
        $stmt->fetch();
        $stmt->close(); // this is where I'm closing the connection
    }
}

在倒数第三行,您会注意到我在 while 循环中关闭了连接。问题是,如果我删除该行,我会在该行得到错误。

致命错误:在非对象上调用成员函数 bind_param()

我猜想关闭连接然后为循环中的下一个元素重新打开它不是一件好事。那么,我该如何解决这个问题?为什么我在移除关闭的连接线时会收到此错误?

4

2 回答 2

0

您可以尝试以下方法:

/* Get the 10 latest posts from users you're following */
$stmt = $cxn->prepare('SELECT * FROM posts WHERE user_id IN (SELECT following_id FROM follows WHERE user_id = ?) ORDER BY datetime DESC LIMIT 15');
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();

/* If a result exists, continue. */
if ($result->num_rows) {
  while ($row = $result->fetch_assoc()) {

    /* Get the user's username from their id */
    $stmt = $cxn->prepare('SELECT username FROM users WHERE user_id = ?');
    $userid = (int)$row['user_id'];
    $stmt->bind_param('i', $userid); // Forcing $row['user_id'] to int
    $stmt->execute();
    $stmt->bind_result($username);
    $stmt->fetch();
    //$stmt->close();  Don't close it here
  }
}
$stmt->close();

另一种方法但更耗时的是:

 /* Get the 10 latest posts from users you're following */
$stmt = $cxn->prepare('SELECT * FROM posts WHERE user_id IN (SELECT following_id FROM follows WHERE user_id = ?) ORDER BY datetime DESC LIMIT 15');
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();

/* If a result exists, continue. */
if ($result->num_rows) {
  while ($row = $result->fetch_assoc()) {

    /* Get the user's username from their id */
    $stmt_loop = $cxn->prepare('SELECT username FROM users WHERE user_id = ?');
    $userid = (int)$row['user_id'];
    $stmt_loop->bind_param('i', $userid); // Forcing $row['user_id'] to int
    $stmt_loop->execute();
    $stmt_loop->bind_result($username);
    $stmt_loop->fetch();
    $stmt_loop->close();  //Close the local stmt here
  }
}
$stmt->close();
于 2013-11-03T23:05:58.290 回答
0

这是我在一个解决此问题的 Github 存储库中获得的示例:

$Query = $Database->prepare("FIRST QUERY");
$Query->execute();
$Query->bind_result($ID,$Password);
$Query->store_result();
   while ($Query->fetch()){

       $Secondary_Query = $Database->prepare("SECOND QUERY");
       $Secondary_Query->bind_param();
       $Secondary_Query->execute();
       $Secondary_Query->close();
   }
$Query->close();

修改它以适合您的工作场景,您将有一个成功的运行查询

于 2013-11-03T23:08:06.203 回答