1

I am able to connect to the database by using the following code.

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
  echo "Connected...!";
?>

But, the above code is just to check whether the connection from PHP to MySQL server is established or not but its no way checking whether the database user is connected with the database name.

Well, I was trying to connect to the database in my project I am unable to connect to it. I have customized error report for that which is not clear but I am able to connect to the database server from PHP using

mysql_connect(servername,username,password);

So, can anybody suggest me some code to test whether the database user is authorized to connect to the database or not?

3
  • 1
    check mysql_select_db() but you should use the mysqli extension instead. will prepare an example Commented Jan 8, 2013 at 3:36
  • 1
    Consider switching to mysqli as the mysql extension you're currently using is deprecated. Commented Jan 8, 2013 at 3:37
  • mysql_ extensions are deprecated in PHP 5.5! Use PDO or MySQLi instead. They're nicer. Commented Jan 8, 2013 at 3:37

1 Answer 1

4

It can be done like this (using the mysqli extension) :

<?php

$link = @mysqli_connect('host', 'user', 'secret');
if(!$link) {
    die('failed to connect to the server: ' . mysqli_connect_error());
}

if(!@mysqli_select_db($link, 'dbname')) {
    die('failed to connect to the database: ' . mysqli_error($link));
}

In my example I used the functional api to mysqli. This works the same way as in the older mysql extension.

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

Comments

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.