【问题标题】:Cannot connect to MYSQL in MAMP using PHP无法使用 PHP 在 MAMP 中连接到 MYSQL
【发布时间】:2016-11-29 10:57:02
【问题描述】:

我刚刚安装了 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 首选项中的端口。我也包括了 or die("Could not connect");在第一行之后,但在页面中的链接数据之后仍然没有得到任何文本。

我在网上查了下,其他有问题的至少看死文字了。我不明白。

我没有更改任何密码或数据,只是弄乱了端口号。

任何帮助将不胜感激!

【问题讨论】:

  • 专业提示:不要使用旧的过时版本的 mysql。而是使用新的和改进的 mysqli_* 扩展或换成 PDO。旧的mysql_* 扩展非常不安全,容易发生 SQL 注入。
  • 您需要通过 PHP 和 MySQL 获取真正的错误。
  • 谢谢。我转换为 mysqi_ 函数,它确实连接了。此外,奇怪的是,必须切换第二个函数中的链接和数据库顺序。

标签: php mysql mamp


【解决方案1】:

请尝试以下方法,我已在本地开发和测试,其中的功能已记录在案,可帮助您了解每个步骤中发生的情况。

    /**
    *
    * 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 文档时尝试将其分解为更小的部分。

【讨论】:

  • 非常感谢您非常彻底的回答。我确实使用 mysql_ 函数进行了连接,但有时间我也会尝试这种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-18
  • 2014-03-28
  • 2010-10-14
  • 2018-12-11
  • 1970-01-01
  • 2011-12-15
  • 2016-11-16
相关资源
最近更新 更多