尝试在嵌入javascript的php页面中使用类

Trying to use a class in a php page embedded with javascript

本文关键字:php javascript      更新时间:2023-09-26

我正在尝试使用一个已经声明的类。

当用户在用户名文本框中键入内容时,我使用了一个javascript函数来加载一个php文件,它会检查用户名是否可用。每次按键都会调用此文件。

到我的数据库的连接是一个类,已经在主页上声明了,但是php文件实际上不能使用数据库类。我能做什么?

如果我写了一个单独的脚本来连接到数据库,它会起作用,但我不想这样做。

Php文件内容:

        $query("SELECT username FROM client WHERE username = :username");
        $query_params = array(
            ':username' => $username
            );
        $db->DoQuery($query);
        $check_num_rows = $db->fetch();
        if ($username == NULL)
            echo 'Choose a Username';
        else if (strlen($username)<=3)
            echo 'too short.';
        else {
            if ($check_num_rows ==0)
                echo "Available!";
            else if ($check_num_rows >= 1)
                echo "Not Available.";
        }
        ?>

body.php

 <script type="text/javascript">
    $(document).ready(function() {
  $('#wowson').load('functions/check_username.php').show();
  $('#username_').keyup(function() {
    $.get('functions/check_username.php', { username: forms.username.value },
      function(result) {
        $('#wowson').html(result).show();
      });
  });    
  });
 </script>
<label>Username:</label><br>
<input id="username_" name="username" required="required" type="text" placeholder="Username"/>
<div id="wowson">
       </div>

数据库类

 class database {
        public function initiate() {
          try
          {
            $this->database = new PDO("mysql:host='host';dbname='db", 'user, 'pass');
          }
          catch(PDOException $e)
          { 
            $error = "I'm unable to connect to the database server.";
            die("Failed to connect to database: " . $e->getMessage());
          }
        }
        public function DoQuery($query, $query_params) {
          try
          {
            $this->result = $this->database->prepare($query);
            if ($query_params != null)
            {
              $this->result->execute($query_params);
            }
            else
            {
              $this->result->execute();
            }
          }
          catch(PDOException $e)
          {
            die();
          }
        }
        public function fetch() {
          return $this->result->fetch();
        }
 }

当您加载原始页面时,您正在从数据库类创建对象,对吗?

好吧,当您使用Ajax向服务器查询用户名时,这是一个全新的请求,它对以前的请求一无所知。

因此,只需在响应ajax请求的PHP脚本中添加require_once('my/path/database.php'); $db = new database();之类的内容。