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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了