I’m a foundation student. My assignment is to create a database for a login system for an html form. I had no problem connecting to it, as well as putting data into the DB. But when I ask my friend to run the form and submit it, it shows this. unknown database alert
Is there some way for my friend to put her data into my DB? This is my code for the DB.
<?php
/* Database credentials. Assuming you are running MySQL server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'membership');
/* Attempt to connect to MySQL database */
$link = mysqli_connect("localhost", "root", "", "membership");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
I would really appreciate it if someone could help me solve this problem.
I tried putting ‘CREATE DATABASE’ and ‘CREATE TABLE IF NOT EXISTS’ into my codes and the result is still the same.
2
Answers
The issue here is you and your friend have different machines each with a different localhost, the first error that you mentioned is related to the database connectivity issues, it can be resolved by properly configuring the right database credentials of her machine, if everything is right and she is still unable to connect to the database, ask her to create the database named
membership
manually by going to her localhost server (most probably MyPHPAdmin). You are usingmysqli_connect()
to connect to your database, it only makes a successful connection if in case themembership
database already exists. To run DB queries (even ifCREATE DATABASE
), you need a successful DB connection upfront (this is why the automatic database creation is not possible and showsCould not connect error
).If both of you need to connect to a single database and make changes from different machines, you’ll need a hosting provider to host your database. Ensure you configure the live database credentials in your
mysqli_connect()
function. Numerous hosting providers offer affordable services (e.g., Namecheap, A2hosting, SiteGround). If cost is a concern, some providers also offer free database hosting.An additional tip, you can also consider taking a backup of your local database and restoring it on the live database or the localhost of her machine. This way, you can populate the live/her database with the necessary data that you already have in your local database.
You have to ensure that database "membership" exists on your friend’s computer. If you want her to connect to your machine then try replacing "localhost" to the Local IP Address of your computer (if you know enough about networks). Last, if you want to create a database using PHP then in your mysqli_connect don’t mention the database name.
$link = mysqli_connect("localhost", "root", "");
Then use this link to execute the CREATE DATABASE query.