简体   繁体   中英

MAMP cannot connect to SQL server within a PHP script

I am quite new to the PHP world. I have installed MAMP on my Mac. This is the code I have written to connect to MySQL:

<?php
// Connect to the database server
$dbcnx = @mysql_connect("localhost", "root", “root”);
if (!$dbcnx) {
  echo( "<P>Unable to connect to the " .
      "database server at this time.</P>" );
  exit();
}
?>

MySQL has already started and is running. I am not sure why am I not able to connect.

Try this

<?php
    // Connect to the database server
    $dbcnx = mysql_connect("localhost", "root", "");
    if (!$dbcnx) {
      echo( "Cannot connect to database  due to ". mysql_error());
      exit();
    }
?>

Since you are getting Access denied for user 'root'@'localhost' (using password: YES) there is no need of giving password to connect with the database.So try with password ''.

Note:- mysql_* functions are deprecated as of PHP 5.5.0,and will be removed in the future.Instead, the MySQLi or PDO_MySQL extension should be used

Your code has smart quotes around the password. Try replacing them with regular quotes. If you have not changed the default MAMP password, this should work:

<?php
// Connect to the database server
$dbcnx = mysql_connect("localhost", "root", "root");
if (!$dbcnx) {
  echo( "<P>Unable to connect to the " .
      "database server at this time.</P>" );
  exit();
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM