【问题标题】:Trying to use a class in a php page embedded with javascript尝试在嵌入 javascript 的 php 页面中使用类
【发布时间】:2014-10-26 16:00:58
【问题描述】:

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

当用户在用户名文本框中输入内容时,我使用了一个 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();
        }
 }

【问题讨论】:

  • 在一个文件的索引中加入数据库连接,使用includerequire将代码包含在新页面中。
  • 您的代码有语法错误。在已经评论的旁边:使用 include / require 或了解自动加载:php.net/manual/en/language.oop5.autoload.php

标签: javascript php pdo


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多