【问题标题】:Query in a class with variable在具有变量的类中查询
【发布时间】:2015-05-07 15:04:18
【问题描述】:

我为我正在处理的网站管理区域创建了一个时钟系统。但我想使用一个类以更好的方式处理代码,所以我重新开始。到目前为止,我有 2 节课。一种通过 PDO 处理数据库连接和对数据库的查询。

在为时钟开始课程时(我必须从头开始构建),因为我在加载页面时不再收到错误消息。但是查询的结果不正确,因为对于来自数据库的记录,我应该返回“true”而不是 NULL。有人可以帮我理解我做错了什么。

我的数据库类是这样的(来自 GitHub)...

/**
 *  DB - A simple database class 
 *
 * @author      Author: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWickyAswal)
 * @git         https://github.com/indieteq/PHP-MySQL-PDO-Database-Class
 * @version      0.2ab
 *
 */
require("Log.class.php");
class DB
{
    # @object, The PDO object
    private $pdo;

    # @object, PDO statement object
    private $sQuery;

    # @array,  The database settings
    private $settings;

    # @bool ,  Connected to the database
    private $bConnected = false;

    # @object, Object for logging exceptions    
    private $log;

    # @array, The parameters of the SQL query
    private $parameters;

       /**
    *   Default Constructor 
    *
    *   1. Instantiate Log class.
    *   2. Connect to database.
    *   3. Creates the parameter array.
    */
        public function __construct()
        {           
            $this->log = new Log(); 
            $this->Connect();
            $this->parameters = array();
        }

       /**
    *   This method makes connection to the database.
    *   
    *   1. Reads the database settings from a ini file. 
    *   2. Puts  the ini content into the settings array.
    *   3. Tries to connect to the database.
    *   4. If connection failed, exception is displayed and a log file gets created.
    */
        private function Connect()
        {
                        $host = 'localhost';
                        $username = 'root';
                        $password = '';
                        $dbname = 'acro_1986';
            //$this->settings = parse_ini_file("settings.ini.php");
            $dsn = 'mysql:dbname='.$dbname.';host='.$host.'';
            try 
            {
                # Read settings from INI file, set UTF8
                $this->pdo = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

                # We can now log any exceptions on Fatal error. 
                $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                # Disable emulation of prepared statements, use REAL prepared statements instead.
                $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

                # Connection succeeded, set the boolean to true.
                $this->bConnected = true;
            }
            catch (PDOException $e) 
            {
                # Write into log
                echo $this->ExceptionLog($e->getMessage());
                die();
            }
        }
    /*
     *   You can use this little method if you want to close the PDO connection
     *
     */
        public function CloseConnection()
        {
            # Set the PDO object to null to close the connection
            # http://www.php.net/manual/en/pdo.connections.php
            $this->pdo = null;
        }

       /**
    *   Every method which needs to execute a SQL query uses this method.
    *   
    *   1. If not connected, connect to the database.
    *   2. Prepare Query.
    *   3. Parameterize Query.
    *   4. Execute Query.   
    *   5. On exception : Write Exception into the log + SQL query.
    *   6. Reset the Parameters.
    */  
        private function Init($query,$parameters = "")
        {
        # Connect to database
        if(!$this->bConnected) { $this->Connect(); }
        try {
                # Prepare query
                $this->sQuery = $this->pdo->prepare($query);

                # Add parameters to the parameter array 
                $this->bindMore($parameters);

                # Bind parameters
                if(!empty($this->parameters)) {
                    foreach($this->parameters as $param)
                    {
                        $parameters = explode("\x7F",$param);
                        $this->sQuery->bindParam($parameters[0],$parameters[1]);
                    }       
                }

                # Execute SQL 
                $this->succes   = $this->sQuery->execute();     
            }
            catch(PDOException $e)
            {
                    # Write into log and display Exception
                    echo $this->ExceptionLog($e->getMessage(), $query );
                    die();
            }

            # Reset the parameters
            $this->parameters = array();
        }

       /**
    *   @void 
    *
    *   Add the parameter to the parameter array
    *   @param string $para  
    *   @param string $value 
    */  
        public function bind($para, $value)
        {   
            $this->parameters[sizeof($this->parameters)] = ":" . $para . "\x7F" . utf8_encode($value);
        }
       /**
    *   @void
    *   
    *   Add more parameters to the parameter array
    *   @param array $parray
    */  
        public function bindMore($parray)
        {
            if(empty($this->parameters) && is_array($parray)) {
                $columns = array_keys($parray);
                foreach($columns as $i => &$column) {
                    $this->bind($column, $parray[$column]);
                }
            }
        }
       /**
    *       If the SQL query  contains a SELECT or SHOW statement it returns an array containing all of the result set row
    *   If the SQL statement is a DELETE, INSERT, or UPDATE statement it returns the number of affected rows
    *
    *       @param  string $query
    *   @param  array  $params
    *   @param  int    $fetchmode
    *   @return mixed
    */          
        public function query($query,$params = null, $fetchmode = PDO::FETCH_ASSOC)
        {
            $query = trim($query);

            $this->Init($query,$params);

            $rawStatement = explode(" ", $query);

            # Which SQL statement is used 
            $statement = strtolower($rawStatement[0]);

            if ($statement === 'select' || $statement === 'show') {
                return $this->sQuery->fetchAll($fetchmode);
            }
            elseif ( $statement === 'insert' ||  $statement === 'update' || $statement === 'delete' ) {
                return $this->sQuery->rowCount();   
            }   
            else {
                return NULL;
            }
        }

      /**
       *  Returns the last inserted id.
       *  @return string
       */   
        public function lastInsertId() {
            return $this->pdo->lastInsertId();
        }   

       /**
    *   Returns an array which represents a column from the result set 
    *
    *   @param  string $query
    *   @param  array  $params
    *   @return array
    */  
        public function column($query,$params = null)
        {
            $this->Init($query,$params);
            $Columns = $this->sQuery->fetchAll(PDO::FETCH_NUM);     

            $column = null;

            foreach($Columns as $cells) {
                $column[] = $cells[0];
            }

            return $column;

        }   
       /**
    *   Returns an array which represents a row from the result set 
    *
    *   @param  string $query
    *   @param  array  $params
    *       @param  int    $fetchmode
    *   @return array
    */  
        public function row($query,$params = null,$fetchmode = PDO::FETCH_ASSOC)
        {               
            $this->Init($query,$params);
            return $this->sQuery->fetch($fetchmode);            
        }
       /**
    *   Returns the value of one single field/column
    *
    *   @param  string $query
    *   @param  array  $params
    *   @return string
    */  
        public function single($query,$params = null)
        {
            $this->Init($query,$params);
            return $this->sQuery->fetchColumn();
        }
       /**  
    * Writes the log and returns the exception
    *
    * @param  string $message
    * @param  string $sql
    * @return string
    */
    private function ExceptionLog($message , $sql = "")
    {
        $exception  = 'Unhandled Exception. <br />';
        $exception .= $message;
        $exception .= "<br /> You can find the error back in the log.";

        if(!empty($sql)) {
            # Add the Raw SQL to the Log
            $message .= "\r\nRaw SQL : "  . $sql;
        }
            # Write into log
            $this->log->write($message);

        return $exception;
    }

}

我的时钟课...

class Timeclock {
    public $user_id;
    public function __construct($user_id) {
        $this->user_id = $user_id ;
        $this->db = new Db();
        //$this->clocked_in = is_user_clocked_in($user_id);
    }
    public function is_user_clocked_in(){
        $result = $this->db->query("SELECT * FROM timeclock WHERE user_id = :user_id AND time_out IS NULL", array("user_id"=>$this->user_id));
        if ( count ( $result ) > 0 ){
            return $result[0];
        }else{
            return null;
        }

    }
}

我这样称呼它......

if (isset($_SESSION['admin'])) {
    $_user_id = $_SESSION['admin'][0]['user_id'];
// calls action and determines case
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
    } else if (isset($_GET['action'])) {
        $action = $_GET['action'];
    } else {
        $action = 'home';
    }
    $action = strtolower($action);
    switch ($action) {
        case 'home':
            $timeclock = new Timeclock($_user_id);
            $user = new Timeclock($timeclock->user_id);
            $clocked_in = $user->is_user_clocked_in();

            include ('dashboard.php');
            break;
    }
}

另外,是否可以让类中的每个函数(一旦完成)一个接一个地运行并在顶部填写声明的变量(当然,一旦我添加了它们),这样我就可以调用该类并运行一次?还是我必须根据需要单独调用每个函数?

【问题讨论】:

  • 可以和我们共享数据库类吗?似乎这里的问题是您的查询失败了,这就是问题所在。此外,您还可以通过执行 if(!$result){ echo $this-&gt;db-&gt;errorInfo(); } 然后退出或类似的事情来添加一些错误报告。假设$this-&gt;db 是您的 PDO 对象的数据库处理程序。
  • 好的,我添加了它......这是一个相当长的课程
  • return $this-&gt;sQuery-&gt;fetchAll($fetchmode); 这是返回空值。你需要弄清楚为什么返回null。 sQuery 是在您的 Init 函数中创建的已执行准备好的语句。我会从那里开始倒退,找出它为什么不起作用。
  • 我对它还不够熟悉,无法开始使用脚本倒退。我真的很想深入研究它并弄清楚它是如何工作的。另一方面,上面的脚本返回了一个我忘记提及的错误。它给了我一个**注意:函数中返回的查询上的数组到字符串转换**错误。
  • 不幸的是,我无法立即确定发生了什么。如果您愿意,可以给我发送电子邮件(查看我的个人资料以获取地址),我很乐意在 S.O. 之外为您提供帮助

标签: php mysql class pdo


【解决方案1】:

感谢您尝试帮助@Ohgodwhy。 $clocked_in 返回一个数组,因为我要求它选择表中的所有列。所以当有结果时,它是一个数组。我将函数的返回更改为返回 true 而不是 $result[0] 因为我只需要知道用户是否已登录。我可能也只是更改了查询以选择该列。这样做之后,它工作得很好,直到我为表字段提供了一个值(使用户时钟输入)。然后我得到一个 Undefined offset:0 错误,因为我试图在没有索引数组时调用 $result[0] 的值,因为查询显然返回 array(0);我只是更改了计数以检查 $result 是否存在。

更新代码如下,以防万一有人遇到这种情况

时钟类

class Timeclock {
    public $user_id;
    public function __construct($user_id) {
        $this->user_id = $user_id ;
        $this->db = new Db();
        //$this->clocked_in = is_user_clocked_in($user_id);
    }
    public function is_user_clocked_in(){
        $result = $this->db->query("SELECT * FROM timeclock WHERE user_id = :user_id AND time_out IS NULL", array("user_id"=>$this->user_id));
        if ( count ($result) > 0 ){
            return true;
        }else{
            return null;
        }

    }
}

【讨论】:

    猜你喜欢
    • 2022-10-17
    • 2018-04-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多