Arslan Ali Awan Arslan Ali Awan - 2 years ago 59
MySQL Question

can't connect to db in my sql

i am using mamp on mac to connect to localhost ,i can connect to server successfully but the problem is i cant connect to db, i don't know in which part of query i making mistake since its just a one line query.i also searched different solutions here on stack overflow but they couldnt helpful

$username = 'root';
$password = 'root';
$host = 'localhost';
$database = 'trendnow';
$link = mysqli_connect($host, $username, $password);

if (!$link) {
echo 'can not connect to the server';
$db_selected = mysqli_select_db($database,$link);
echo $db_selected;
if (!$db_selected) {

echo 'Can not connect to trend now ';

Answer Source

Felippe Duarte is correct. What is the database you are trying to connect to?

  • Localhost means connect to the server that the program is running on. Sometimes people will connect to a database located on a server that is not local, so this will sometimes be an IP address.
  • my_db is the name of the database. So if your database was called WebStore, you may have a table located on the database called, computers. The WebStore would be the name of the database and must reside in that last section, like so: mysqli_connect("localhost","my_user","my_password","WebStore");

Here is a tutorial that may help.

Getting a useful error message

The problem with the stand alone connection is that if there is an error, it won't tell you what it is. Thankfully there are a few ways to find out what the error is.

$con = mysqli_connect("localhost","my_user","my_password","my_db");

//This will check if we were able to start up a connection using the above line
if (mysqli_connect_errno())
  echo "Failed to connect to MySQL: " . mysqli_connect_error();

// This is an example query. We will check if it failed, and if so, why it failed
// Perform a query, check for error
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')"))
  echo("Error description: " . mysqli_error($con));


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download