3

This is my situation:

I'm trying to connect to my MySQL database with a PHP file on my Apache server, now: my PHP can connect to the MySQL database when I run it from the terminal (using "php -f file.php") but when I execute it from a web page it just doesn't connect.

This is my php file:

echo "TRY CONNECTION";
$conn = mysql_connect($servername, $username, $password);
echo "EXECUTED CONNECTION";

The Linux shell prints this:

TRY CONNECTIONEXECUTED CONNECTION

But the web page prints this:

:TRY CONNECTION

I tried using mysqli but the result is the same

aynber
  • 22,380
  • 8
  • 50
  • 63
Daniele Navarra
  • 159
  • 2
  • 13
  • 1
    Check for mysqli_error() after your connection, and check your error logs on the server. Stay away from the mysql_* functions as they've been removed in PHP7 and deprecated in all previous versions because they are horribly insecure. – aynber Jan 26 '17 at 17:00
  • How are you setting $servername, $username, and $password? Please provide just sample credentials and not your actual ones! – AvatarKava Jan 26 '17 at 17:00

2 Answers2

0

try this

 echo "TRY CONNECTION";
 $conn =new mysqli($servername, $username, $password,$database);
 echo "EXECUTED CONNECTION";

or may be this

$con = mysqli_connect("localhost","my_user","my_password","my_db");
M. Alim
  • 153
  • 16
  • It's much better to use the object-oriented interface: [`new mysqli(...)`](http://php.net/manual/en/mysqli.construct.php) than the procedural style. Not only is it less verbose, but it avoids mistakes with using `mysql_query` by accident. – tadman Jan 26 '17 at 17:31
0

Which MySQL version you use?

define('HOST_NAME', 'localhost');
define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASS', '');
// DB Connections
$db = mysql_connect(HOST_NAME, DB_USER, DB_PASS);
if($db){
    if(mysql_selectdb(DB_NAME, $db)){
        //echo 'DB Connected.';
    }else{
        echo mysql_errno();
    }
}else{
    echo mysql_error();
}

or used below one
// Create connection
$conn = new mysqli(HOST_NAME, DB_USER, DB_PASS);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
Mizanur Rahman Khan
  • 1,612
  • 1
  • 12
  • 19