首页 > 解决方案 > 一次调用后 SQL 连接断开

问题描述

我有一个将 sql 连接作为参数的自定义类。我用它来填充类,然后我试图再次使用它来修改屏幕上的结果。但第一次使用后,我不能再使用它了。

连接.php:

$conn = new mysqli('localhost', 'root', '', 'loveConnections');
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
} 

personalityProfile.php(前端)

if (!isset($_SESSION['interests'])) {
    $interests = new Interests($conn, $_SESSION['id']);
    $_SESSION['interests'] = $interests;
} else {
    $interests = $_SESSION['interests'];
}

兴趣对象.php

class Interests {

  // properties
  public $conn;
  public $id;
  public $interestsArray = [];

  public function __construct($conn, $memberId = null, $intArray = [
    'basketball' => false,
    'bowling' => false,
    'movies' => false,
  ]) {
    $this->conn = $conn;
    $this->id = $memberId;
    $this->interestsArray = $intArray;
    $this->popArraySql();
  }

  public function popArraySql() {
    $memInterests = [];
    $sql = "SELECT i.interest
              FROM memberInfo m
              Join MemberInterestLink mi on (mi.memberID_FK = m.memberID_PK)
              Join interests i on (mi.interestID_FK = i.interestID_PK)
              WHERE memberID_PK = $this->id";
    $result = $this->conn->query($sql);

$this->conn在这里完美运行

    foreach ($result as $row) {
      array_push($memInterests, $row['interest']);
    }

    foreach ($this->interestsArray as $key => $value) {
      for ($i=0; $i<sizeof($memInterests); $i++) {
        if ($memInterests[$i] === $key) {
          $this->interestsArray[$key] = true;
        }
      }
    }
  }

  public function insertUpdateQuery() {
    var_dump($this->conn);
    foreach ($this->interestsArray as $key => $val) {
      echo $key . "<br>";
      $select = "SELECT interestID_PK from interests where interest = '" . $key . "'";
      echo $select;
      $result = $this->conn->query($select);

不过,当我稍后尝试使用它时,我得到一个Warning: mysqli::query(): Couldn't fetch mysqli. 此外,如果我尝试 var_dump 它,我会得到Warning: var_dump(): Property access is not allowed yet

      var_dump($result);
      if ($val === true) {
        $insert = "INSERT INTO MemberInterestLink (memberID_FK, interestID_FK) VALUES ($this->id, $interestKey)";
        $this->conn->query($insert);
      } else {
        $delete = "DELETE FROM MemberInterestLink WHERE interestID_FK = $interestKey";
        $this->conn->query($delete);
      }
    }
  }
}

我从不关闭连接,这是大多数相关答案所暗示的原因。就像我的 $conn 变量在第一次使用后停止工作。

标签: phpmysql

解决方案


推荐阅读