Cannot Connect to MySQL with PHP, please help!

I just started working through the book “Build Your Own Database Driven Website, 4th ed”, I’ve searched the forums endlessly, but I’m still running into a dead end and fear I cannot continue learning.

Several people in the Questions About Books forums are having trouble with the Connecting to MySQL with PHP section on page 117. The code is here:

<?php
$link = mysqli_connect(‘localhost’, ‘root’, ‘password’);
if (!$link)
{
$output = ‘Unable to connect to the database server.’;
include ‘output.html.php’;
exit();
}

if (!mysqli_set_charset($link, ‘utf8’))
{
$output = ‘Unable to set database connection encoding.’;
include ‘output.html.php’;
exit();
}

if (!mysqli_select_db($link, ‘giggify’))
{
$output = ‘Unable to locate the joke database.’;
include ‘output.html.php’;
exit();
}

$output = ‘Database connection established.’;
include ‘output.html.php’;
?>

I have entered into the ‘password’ parameter my password which works in the Terminal to access MySQL. When I type ‘localhost/connect/’ into my Chrome browser (I’m running MAMP 5.3.6 on a Mac OSX 10.6.8), I get the $output value for the first if statement (Unable to connect to the database server). If I remove the ‘root’ parameter in mysqli_connect function, I get the $output value for the last if statement (Unable to locate the joke database).

If you could help steer me in the right direction I would really appreciate it. I’m loving this book and want to learn more!

Try changing the line:

$link = mysqli_connect('localhost', 'root', 'password');

To:

$link = mysqli_connect('localhost', 'root', 'password') or die(mysql_error());

That will show why it is not connecting.

You could also try this; (from the php manual)


<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_error());
}
?>

Thanks for the response! The error message I’m getting is this:

No Data Recieved: Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.

It looks like perhaps, using social_xperiments suggestion, that my username is not ‘root’. I don’t remember picking a username on MySQL. Any idea how I could figure out what it is? Thanks so much for the help guys!

If MAMP is anything like XAMPP you should be able to view the SQL users under “Privileges” inside phpmyadmin (or something similar);

The problem was with the directory location.