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

最後から 3 行目で、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 に答える