Checking MySQL connection

He has: 698 posts

Joined: Jul 2005

I have looked across the web for this, and the two examples I have found just aren't working for me, so I'm hoping someone here has a solution.

I am working on an install page for one of my new scripts, and it has two main steps:

1. Insert MySQL connection details (host, database, user, password)
2. Insert General Configuration details (Username, Password, Name, Email, etc...for the administrator)

Steps 1 and 2 are separate pages (still contemplating whether or not I want to do that, but they can easily be combined. However, when I go from step 1 to step 2, the first thing I'd like to be able to do is check if the MySQL details work. I know how to connect to MySQL, obviously, but I'm not sure how I could create some sort of if..else statement to check those details. I know if I try to connect, and it can't, it will stop the script and show an error message, but if it can't connect, I'd like for it to show an error message and return to the original form.

I would prefer to use solely PHP to do this, but if there is some way to use JavaScript to assist, that would be fine. Thanks.

Kurtis

Greg K's picture

He has: 2,145 posts

Joined: Nov 2003

Try something like this:

<?php
    $dbConn
= @mysql_connect($host,$user,$pass);

    if (!
$dbConn)
    {
        echo \
"Could not Connect to database server with values given\";
        // Other code here...
    }

    if (!@mysql_select_db(
$database,$dbConn))
    {
        echo \"Could not access database on the server\";
        // Other code here...
    }

   
$sql = \"CREATE TEMPORARY TABLE `tmp123456` (id int)\";
    if (!@mysql_query(
$sql))
    {
        echo \"Did not have permission to create tables\";
        // Other code here
    }
   
   
$sql = \"INSERT INTO `tmp123456` VALUES(1)\";
    if (!@mysql_query(
$sql))
    {
        echo \"Did not have permission to insert data\";
        // Other code here
    }
   
    if (
$dbConn) mysql_close($dbConn);
   
    echo \"Database values look good!\";
?>

He has: 698 posts

Joined: Jul 2005

Thanks. That works wonderfully. I wrote something nearly identical to this earlier, and it wasn't working. I probably had a ')' out of place; I've done that so many times.

Thanks again. Wink

Kurtis

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.