I want a website to connect to a database with a connect.php so i created a small test in it. but it is failing only showing Database Connection Failed with no mysql error. here is the code:
<?php
$servername = "localhost";
$username = "sqluser";
$password = "Welkom01!";
$dbname = "users";
$connection = mysqli_connect('$servername', '$username', '$password');
if (!$connection){
die("Database Connection Failed". mysqli_error());
}
$select_db = mysqli_select_db($dbname);
if (!$select_db){
die("Database Selection Failed" . mysqli_error());
}
echo "succes";
?>
could you guys help me out? thanks in advance
Remove the single quotes around your variables:
$connection = mysqli_connect($servername, $username, $password');
PHP treats the contents of single quotes as strings. Only double quotes will evaluate variables correctly:
<?php
$username = 'foo';
echo '$username'; // outputs: '$username'
echo "$username"; // outputs: 'foo';
echo $username; // outputs : 'foo';
Also, your mysqli_select_db
is incorrect. It should be:
$select_db = mysqli_select_db($connection, $dbname);
As Fred pointed out below, mysqli_error requires the connection to be passed in:
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
If you use single quotes in a method/function, the interpreter will not assign the variable value.
A solution might be:
$connection = mysqli_connect($servername, $username, $password);
You also need to pass the linkid ($connection) when selecting your database.
$select_db = mysqli_select_db($connection, $dbname);
Try this :
<?php
$servername = "localhost";
$username = "sqluser";
$password = "Welkom01!";
$dbname = "users";
$connection = mysqli_connect($servername, $username, $password);
if (!$connection){
die("Database Connection Failed". mysqli_error($connection));
}
$select_db = mysqli_select_db($connection,$dbname);
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
echo "succes";
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.