Agent Coop
Agent Coop

Reputation: 390

PHP, can't connect to the MySQL server

What might be the reason of the following problem.

PHP function mysql_connect() works fine if I execute it from command line (php -r "mysql_connect('127.0.0.1', 'db_user', 'db_pass');").

The same call with the same parameters fails for PHP running as an Apache module.

MySQL server is running remotely, connection to it is forwarded using SSH: ssh -fN -L 3306:localhost:3306 remote_host

Any ideas what might be wrong?

Upvotes: 0

Views: 425

Answers (2)

Anthony Rutledge
Anthony Rutledge

Reputation: 7574

Based on your question and details, I would say that the MySQL server is refusing to connect to your web server (where ever it is) because the connection is not secure (in one fashion or another). If you want to connect via the PHP module in Apache as easily as you do from the command line, set up your connection so that all encryption/ tunneling issues are resolved. That's what I would do.

However, make sure the following line is correct..

mysql_connect('127.0.0.1', 'db_user', 'db_pass');"

Are you pointing to the correct server? I thought you said that the MySQL server was remote. This line suggests that you are attempting to connect to a local, imaginary MySQL server that is running on the same machine as the web server. Try getting the IP or domain name of the MySQL server and use that instead (in your web code, that is).

Upvotes: 1

l0gic
l0gic

Reputation: 131

You'll want to be looking at using MySQLi or PDO as the older MySQL functions are deprecated.

This should help get you started:

<?php
//establish conection
$link = mysqli_connect("host","user","pass","bd") or die("Error: " . mysqli_error($link));

$query = "SELECT name FROM mytable" or die("Error: " . mysqli_error($link));

//execute query
$result = $link->query($query);

//display information
while($row = mysqli_fecth_array($result)) {
  echo $row["name"] . "<br>";
} 
?>

Upvotes: 1

Related Questions