1

Just installed MAMP and am learning about php and connecting to my databases. I seem to be able to connect to mysql but can't connect or see any databases in phpMyAdmin.

Here's my php code:

<?php

$user = 'root';
$password = 'root'; 
$db = 'test';
$host = 'localhost';

$link = mysqli_connect($host, $user, $password);

//newly editied
if ($link->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
        . $mysqli->connect_error);
}

$db_selected = mysqli_select_db($db, $link);

if (!$db_selected) {
   echo "did not connect";
}
?>

When I run it, I'll get the words "good", so I know I'm connecting, followed by "did not connect", so it's not connecting to my database.

I've also tried adding this code and nothing gets echoed at all even though I have several databases created.

$res = mysqli_query("SHOW DATABASES");

while ($row = mysqli_fetch_assoc($res)) {
    echo $row['Database'] . "\n";
}

Any help is appreciated!

1 Answer 1

2

You are wrong when checking the connection status.

You use:

if ($link) {
    echo "good";
}

And should use:

if ($link->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

As per the PHP documentation, mysqli_connect() will always return an object, so it will never be false.

You also inverted parameters $db and $link on DB selection, and used an improper function in consideration of your previous code. It should be

$mysqli->select_db($db)

And not:

$db_selected = mysqli_select_db($db, $link);

which in correct order is in fact:

$db_selected = mysqli_select_db($link, $db);

Read the mysqli_select_db() PHP documentation for more details on proper use.

Sign up to request clarification or add additional context in comments.

1 Comment

Just changed my code, thanks. But there doesn't seem to be an error with connecting to mysqli... I still can't connect to any databases. Or show any of them, for that matter. Any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.