2
votes

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

2
How are you setting $servername, $username, and $password? Please provide just sample credentials and not your actual ones!AvatarKava
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

2 Answers

0
votes

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");
0
votes

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";