我刚刚安装了 MAMP 并创建了一个 MYSQL 数据库。我可以通过 PHPMYADMIN 访问它。
在我的 php 页面中,我有这个,直接从 MAMP webstart 页面粘贴--
$user = 'root';
$password = 'root';
$db = 'local_db';
$host = 'localhost';
$port = 3306;
$link = mysql_connect(
"$host:$port",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
生成的页面此时停止,不会打印低于这些说明的任何内容。
我尝试更改 MAMP 首选项中的端口。我也包括或死亡(“无法连接”);在第一行之后,但在页面中的链接数据之后仍然没有得到任何文本。
我在网上查了一下,其他有问题的人至少看到了死文。我不明白。
除了弄乱端口号之外,我没有更改任何密码或数据。
如有任何帮助,我们将不胜感激!
最佳答案
请尝试以下操作,我在本地开发并测试了它,其中的功能已记录下来,以帮助您了解每一步发生的情况。
/**
*
* Modern method of connecting to a MySQL database and keeping it simple.
*
* If you would like to learn more about PDO,
* please visit http://php.net/manual/en/book.pdo.php
*
*/
//Set up database connection constants, so they cannot be changed.
define('DBHOST','127.0.0.1'); //Change this to the ip address of your database
define('DBNAME','test'); // Change this to the database name you are trying to connect to.
define('DBUSER','databaseuser'); // Insure this user is not the root user!!!!
define('DBPASS','databasepassword'); // Insure this is not the root password!!!!
//Let's try to connect to the database first.
try {
//Initiate a new PDO object called $MYDB and pass it the proper information to make
//the connection
$MYDB = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME."", DBUSER, DBPASS);
//If we are successful show it :D for the test page, if this is for production you should not show this.
echo "Database connection was successful.";
//If this does not worth catch the exception thrown by PDO so we can use it.
} catch(PDOException $e) {
//Show that there was an issue connecting to the database. Do not be specific because,
//user's do not need to know the specific error that is causing a problem for security
//reasons.
echo "Oh, sorry there was an issue with your request please try again.";
//Since we had an issue connecting to the database we should log it, so we can review it.
error_log("Database Error" . $e->getMessage());
}
//Since this is 100% php code we do not need to add a closing php tag
//Visit http://php.net/manual/en/language.basic-syntax.phptags.php for more information.
如果您对此有任何问题,请在查看 PDO 文档时尝试将其分解为更小的部分。
关于php - 无法使用 PHP 连接到 MAMP 中的 MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38578944/