热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

即使已连接,PHP也不能选择数据库-PHPcannotselectdatabaseeventhoughconnected

JustinstalledMAMPandamlearningaboutphpandconnectingtomydatabases.Iseemtobeabletoc

Just installed MAMP and am learning about php and connecting to my databases. I seem to be able to connect to mysql but can't connect or see any databases in phpMyAdmin.

刚刚安装了MAMP,正在学习php和连接到我的数据库。我似乎可以连接到mysql,但不能连接或看到phpMyAdmin中的任何数据库。

Here's my php code:

这是我的php代码:

connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
        . $mysqli->connect_error);
}

$db_selected = mysqli_select_db($db, $link);

if (!$db_selected) {
   echo "did not connect";
}
?>

When I run it, I'll get the words "good", so I know I'm connecting, followed by "did not connect", so it's not connecting to my database.

当我运行它时,我将会得到“good”,所以我知道我正在连接,接着是“没有连接”,所以它没有连接到我的数据库。

I've also tried adding this code and nothing gets echoed at all even though I have several databases created.

我也尝试过添加这段代码,即使我创建了几个数据库,也没有得到任何响应。

$res = mysqli_query("SHOW DATABASES");

while ($row = mysqli_fetch_assoc($res)) {
    echo $row['Database'] . "\n";
}

Any help is appreciated!

任何帮助都是赞赏!

1 个解决方案

#1


2  

You are wrong when checking the connection status.

检查连接状态时出错。

You use:

你使用:

if ($link) {
    echo "good";
}

And should use:

而且应该使用:

if ($link->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

As per the PHP documentation, mysqli_connect() will always return an object, so it will never be false.

根据PHP文档,mysqli_connect()将始终返回一个对象,因此它永远不会是假的。

You also inverted parameters $db and $link on DB selection, and used an improper function in consideration of your previous code. It should be

在选择db时,您还反转了参数$db和$link,并在考虑到以前的代码时使用了不正确的函数。它应该是

$mysqli->select_db($db)

And not:

而不是:

$db_selected = mysqli_select_db($db, $link);

which in correct order is in fact:

正确的顺序是:

$db_selected = mysqli_select_db($link, $db);

Read the mysqli_select_db() PHP documentation for more details on proper use.

阅读mysqli_select_db() PHP文档,了解更多关于正确使用的详细信息。


推荐阅读
author-avatar
祢好世界末日
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有