-2

Unable to connect to mysql through php. Gives an error,

Can't connect to MySQL server on 'localhost' (10061).

I'm using MAMP on Windows

 <?php
   $host_name="localhost";
   $db_name="baby_names";
   $username="root";
$password="";
$con=mysql_connect($host_name,$username,$password);


if (!$con) {
    echo "Connection failed: " ;
    die(mysql_error());
}
else
echo "connected successfully";

?>
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Chaitanya Krish
  • 55
  • 1
  • 1
  • 7
  • 1
    If you can, you should [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really not hard](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Oct 12 '15 at 16:07
  • Have you started MySQL in your MAMP console? – Jay Blanchard Oct 12 '15 at 16:08
  • yes the mysql is started in the mamp – Chaitanya Krish Oct 12 '15 at 16:10
  • I'm using php 5.6.8, so I think mysql should work – Chaitanya Krish Oct 12 '15 at 16:10
  • 1
    It *should* work but you *shouldn't* be using it. – Jay Blanchard Oct 12 '15 at 16:11
  • Yeah changed everything to mysqli but still no good. gives the same eroor – Chaitanya Krish Oct 12 '15 at 16:15
  • I wouldn't expect changing it to fix the problem, but you should definitely not use the mysql_ extension anyway, for plenty of other reasons... Bear in mind that [MAMP runs MySQL on port 8889 by default](https://www.mamp.info/en/documentation/), rather than the normal 3306, so you'll probably need to specify the port as well as the hostname. – Matt Gibson Oct 12 '15 at 16:20

2 Answers2

1

I'm not sure but this works for me. You also need to give the user access with

"GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' IDENTIFIED BY '%s'";

(Source)

This a piece of of code i use and it works on several systems.

<?php
$hostname = "127.0.0.1";
$user = "xxx";
$pass = "xxx";
$scheme = "xxx";
$conn = mysqli_connect($hostname, $user, $pass, $scheme);

if(!$conn) {
     die(mysqli_error($conn));
}
else {
     die("SUCCES!!!");
}
?>
Community
  • 1
  • 1
Deben Oldert
  • 114
  • 1
  • 11
0

You'll probably have to grant 'localhost' privileges to on the table to the user. See the 'GRANT' syntax documentation. Here's an example (from some C source).

GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' IDENTIFIED BY '%s';

That's the most common access problem with MySQL.