mysqli错误:未选择数据库

时间:2017-04-29 17:53:52

标签: php mysqli

我正在尝试创建一个特定的类来管理常见的数据库函数。 这个类看起来像这样:

class DataManager extends PropertyObject
{

private static $dbHost = DB_HOST;
private static $dbUser = DB_USER;
private static $dbPass = DB_PASS;
private static $dbName = DB_NAME;
protected static $conn;

//METHODS:
protected static function openConnection()
{

    if( self::$conn == null ){
        self::$conn = new mysqli(self::$dbHost, self::$dbUser, self::$dbPass, self::$dbName);
        self::$conn->set_charset('utf8');
    }


    if (self::$conn->connect_error) {
        echo "Database connection error";
        exit();
    }

}

protected static function closeConection()
{
    //DataManager::$conn->close();
}

protected static function executeQuery($query)
{
    self::openConnection();

    $result = self::$conn->query($query);

    self::closeConection();
    return $result;
}

protected static function persist($query, $object)
{

    self::openConnection();


    if ($stmt = self::$conn->prepare($query)) {

        $stmt = self::bindParams($stmt, $object);

        $stmt->execute();

        $stmt->close();

    }
    var_dump(self::$conn);

    self::closeConection();


}

protected static function find($query, $params)
{

    self::openConnection();

    if ($stmt = self::$conn->prepare($query)) {

        call_user_func_array(array($stmt, 'bind_param'), self::refValues($params));

        $stmt->execute();
        $result = $stmt->get_result();


        $town = PropertyObject::build_objects($result, array('Town'));

        return $town;

    }


}

protected static function refValues($params)
{

    $refs = array();
    foreach ($params as $key => $value)
        $refs[$key] = &$params[$key];

    return $refs;
}

protected static function bindParams($stmt, $object)
{

    $reflect = new ReflectionClass($object);
    $objectType = $reflect->getShortName();

    $stmt = call_user_func(__NAMESPACE__ . '\\' . $objectType . 'DataManager::bind' . $objectType . 'Params', array($stmt, $object));

    return $stmt;

}

我正在使用调用persist()方法的函数:

public static function persistTown(Town $town) {

    $query = "INSERT INTO town (name, picture, population) VALUES (?, ?, ?)";

    DataManager::persist($query, $town);


}

当我尝试持久化城镇时,persist方法调用openConnection方法,如果尚未创建连接,则此方法创建连接: self::$conn = new mysqli(self::$dbHost, self::$dbUser, self::$dbPass, self::$dbName);

问题在于,当我执行var_dump(self::$conn)时,我得到了这个: public 'errno' => int 1046 public 'error' => string 'No database selected' (length=20)

如果删除连接检查,问题就会消失: if( self::$conn == null ){

我做错了什么?

0 个答案:

没有答案