数据库连接的OOP代码无法正常工作

时间:2015-07-22 19:22:56

标签: php oop mysqli

在引用的副本中,我没有看到任何可以帮助我的东西。显然我正在错误地使用该对象,希望有人能指导我正确实现。

使用以下代码我看到创建了Mysql的实例。直接在Mysql.php mysql连接函数中的查询正确运行。但是如何在我创建Mysql实例的check_email.php文件中运行该查询?

在我的日志中,我看到了消息:

  • "在Mysql中,DB连接工作" - 来自Mysql.php第29行

  • "返回1行" - 来自Mysql.php的第33行

  • "数据库连接工作" - 来自check_email.php的第42行

  • "电子邮件= XXXXXX" - 来自check_email.php的第46行

  • " SANITIZED email = xxxxxxx - 来自check_email.php的第51行

然后就死了!

我没有尝试过任何工作。

类DatabaseException:

    <?php
class DatabaseException extends Exception {
}
?>

班级数据库

<?php
abstract class Database {

    protected $login;

    protected $password;

    protected $database;

    protected $hostname;


    public function __construct($login, $password, $database, $hostname) {

        // NB: password not checked and may be empty

        $this->throwExceptionIfNotSet('login', $login);

        $this->throwExceptionIfNotSet('database', $database);

        $this->throwExceptionIfNotSet('hostname', $hostname);



        $this->login    = $login;

        $this->password = $password;

        $this->database = $database;

        $this->hostname = $hostname;

    }


    private function throwExceptionIfNotSet($argName, $argValue) {

        if (empty($argValue)) {

            file_put_contents('/var/log/php/p2bfit.log',"\r\n'${argName}' not set",FILE_APPEND | LOCK_EX);
            throw new DatabaseException("'${argName}' not set");

        }

    }

}
?>

类mysql - Mysql.php

<?php
class Mysql extends Database {

    private $link = null;

    public function __construct($login, $password, $database, $hostname) {

        parent::__construct($login, $password, $database, $hostname);

        $this->connect();

    }


    public function connect() {
        if (! is_null($this->link)) {
            file_put_contents('/var/log/php/p2bfit.log',"\r\nDB was already set",FILE_APPEND | LOCK_EX);
            return;

        }

        $link = new MySQLi($this->hostname, $this->login, $this->password,$this->database);
        if($link->connect_errno){
            file_put_contents('/var/log/php/p2bfit.log',"\r\nDB connection failed",FILE_APPEND | LOCK_EX);
            exit();
        } else {
            file_put_contents('/var/log/php/p2bfit.log',"\r\nIN Mysql the DB connection WORKED",FILE_APPEND | LOCK_EX);

            $res = $link->query("SELECT email from pledges WHERE email = 'rich@fdu.edu'");
            $rows = $res->num_rows;
            file_put_contents('/var/log/php/p2bfit.log',"\r\nReturned $rows Rows",FILE_APPEND | LOCK_EX);
        }

        if (!$link) {
            file_put_contents('/var/log/php/p2bfit.log',"\r\nNo database connection",FILE_APPEND | LOCK_EX);
            throw new DatabaseException(

                sprintf(

                    'Cannot connect to database. mysql_connect() to %s with login %s and password %s fails',

                    $this->hostname,

                    $this->login,

                    $this->password

                )

            );

        }

    }

}
?>

PHP脚本check_email.php

<?php
include('classes/DatabaseException.php');
include('classes/Database.php');
include('classes/Mysql.php');
include('../../lib/logger.php');


//check we have email post var
if(isset($_POST["email"])){
    //check if its ajax request, exit script if its not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest'){
        log_message('NOT AN AJAX REQUEST');
        die('Not ajax request');
    }

    //try connect to db using classes
    try {
        $ini = parse_ini_file('app.ini');

        $connecDB = new Mysql($ini['username'], $ini['password'], $ini['database'], $ini['host']);


    } catch (DatabaseException $ex) {

        log_message('redirect to custom error page would have to happen');

    }

    if(!isset($connecDB)){
        file_put_contents('/var/log/php/p2bfit.log',"\r\nDB connection DID NOT WORK",FILE_APPEND | LOCK_EX);
    } else {
        file_put_contents('/var/log/php/p2bfit.log',"\r\nDB connection WORKED",FILE_APPEND | LOCK_EX);
    }

    //trim and lowercase email
    $email =  strtolower(trim($_POST["email"])); 
    log_message('email= ' . $email);

    //sanitize email
    $email = filter_var($email, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
    log_message('SANITIZED email= ' . $email);

    //check email in db
/************************************************************ 
These attempts just DIE! Don't even get to the if statement.
What am I doing wrong? 
How do I use my new instance to run a query?
*************************************************************/
    $results = mysqli_query($connecDB,"SELECT email FROM pledges WHERE email='$email'");
    // $results = $connecDB->query("SELECT email from pledges WHERE email = 'something@xxx.edu'");
    $rows = $results->num_rows;
    if(!$results){
        log_message("QUERY FIAILED $mysqli->error ");
    } else {
        log_message('RESULTS:' . print_r($results,true));
    }

    //return total count
    $email_exist = mysqli_num_rows($results); //total records
    log_message('EMAIL EXISTS: ' . $email_exist);

    //if value is more than 0, email is not available
    if($email_exist) {
        die('<img src="img/not-available.png" /> the email <b>' . $email . '</b> is already in our database');
    }else{
        // die('<img src="img/available.png" />');
        die('');
    }

    //close db connection
    mysqli_close($connecDB);
}
?>

0 个答案:

没有答案