Looking for Help with PHP connect

Warning : mysqli_select_db() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\elegance\storescripts\connect.php on line 18
Notice : Undefined variable: dbname in C:\xampp\htdocs\elegance\storescripts\connect.php on line 20
Warning : mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\elegance\storescripts\connect.php on line 20
Failed to connect to database

please i need help with this. i am new to php. below is my code


//Step 1; create a database connection
	$con = mysqli_connect(HOST, USER, PASSWORD);
	// check if connection is successful
		die("Database connection failed" . mysqli_error());

//Step 2: connect to a database

$db = mysqli_select_db(DATABASE, $con);
	die("Failed to connect to database {$dbname}" . mysqli_error());

Just instantiate the database properly,

mysqli_connect("", "my_user", "my_password", "my_db");

In this line, you’ve put $con and DATABASE the wrong way around. You can see here that mysqli_select_db expects the database link that you created with mysqli_connect, then the database name. The line below should work:

mysqli_select_db($con, DATABASE);

The return value of mysqli_select_db will be true if the connection to the db is successful, false otherwise; unless you’re doing error checking you can ignore the return value.

As @astonecipher mentioned above, you can also make the connection in one call with the following:

$con = mysqli_connect(HOST, USER, PASSWORD, DATABASE);

As a final thing; while this is a very quick and easy way to get started playing with databases and PHP, it’s not considered the best practice. The current state of the art for connecting with databases in PHP is to use the PDO class.

Sponsor our Newsletter | Privacy Policy | Terms of Service