PHP数据库类或使用该类的代码不起作用

时间:2017-03-08 23:50:53

标签: php mysql oop xampp

您好我已经为我的数据库制作了Php类,我在Windows 10上使用XAMPP。

似乎出现问题,我找不到问题,我不知道它是在我的类文件中还是在我的inex.php文件中

这是错误:

致命错误:未捕获错误:在D:\ XAMP \ htdocs \ telepol \ userInfo.php中找不到类'db':5堆栈跟踪:#0 D:\ XAMP \ htdocs \ telepol \ userInfo.php(43) :第5行的D:\ XAMP \ htdocs \ telepol \ userInfo.php中抛出showData()#1 {main}

db.php中

<? php
class db{
  private $_conn;
  private $_host = "localhost";
  private $_username = "root";
  private $_psw = "";
  private $_dbName = "users";

  public function __construct(){
    $this->_conn = new mysqli($this->_host, $this->_username, $this->_psw, $this->_dbName);

    if ($this->_conn->connect_error){
        die("Connection failed: " . $this->_conn->connect_error);
    }
  }

  public function getCon(){
    return $this->_conn;
  }
}
?>

userInfo.php

<?php
require_once 'classes/db.php';

function showData(){
  $conn = new db();
  $br = 1; //br is used to displat the number of each row in the table.

  $userQuery = "SELECT* FROM users";
  $result = $conn->getCon()->query($userQuery);
  if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
      echo "<tr> <td>" .$br ."</td> <td>" .$row["first_name"] ."</td> <td>" .$row["last_name"] ."</td> <td>" .$row["nickname"] ."</td> <td>" .$row["user_id"] ."</td> <br>" ;
      $br ++;
    }
  }
  $conn->close();
}
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Users Info</title>
    <!-- adding JS scripts -->
    <script type="text/javascript" src="jquery-3.1.1.min.js"></script>
    <!-- adding css -->
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- my CSS -->
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    <table class="table table-striped table-bordered table-hover table-sm">
      <thead class="thead-default">
        <tr>
          <th>#</th>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Nickname</th>
          <th>User ID</th>
        </tr>
      </thead>
      <?php showData(); ?>
    </table>
  </body>
</html>

1 个答案:

答案 0 :(得分:-1)

你的$ conn变量不是连接而是包装器,而是你的连接在:$ conn-&gt; getCon()

所以你可以使用:

$result = $conn->getCon()->query($userQuery);