问题
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
回答1:
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");
回答2:
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";
来源:https://stackoverflow.com/questions/41878840/connection-of-mysql-with-php-not-working