duanpanbo9476 2014-05-28 04:55
浏览 38
已采纳

mysqli中的“没有数据库选择”(php)

i get the "No database selected" using mysqli in php, i have this method:

private static $db_server = "localhost";
private static $db_usuario = "root";
private static $db_clave = "";
private static $db_base = "test";
private static $db = null;
public static function conectar_db() {
    if (self::$db == null) {
        self::$db = new mysqli(self::$db_server,self::$db_usuario,self::$db_clave,self::$db_base);
        self::$db->connect();
    }
    return self::$db;
}

and this code in another file to execute a query:

    $db = Core::conectar_db();
    $r = $db->query("SELECT * FROM usuarios");
    echo $db->error;//temporal
    while ($row = $r->fetch_array()) {
        var_dump($row);
        echo "<br>";
    }

and when executing the code the complete output is:

    No database selected
Fatal error: Call to a member function fetch_array() on a non-object in Path\to\my\file.php on line 6

but if i change the query to test.usuarios instead of usuarios it works (i'm using var_dump just for testing), i tried:

  • using public static $db and accesing directly to Core::$db (Core is a class to handle these core functionality)
  • using &conectar_db in method's signature
  • adding an invalid database name to $db_base and i got an error saying that db is invalid as expected i must use oop (i think using procedural style would have the same results as oop methods) because this is a project
  • 写回答

1条回答 默认 最新

  • duanluangua8850 2014-05-28 05:01
    关注

    Don't call self::$db->connect(). The mysqli constructor connects to the server. The connect method is actually equivalent to the constructor, so you're reconnecting with default parameters when you call connect() with no arguments.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式