No database selected error message

2020-02-15 07:38发布

问题:

I am changing all my queries that are using PHP MySQL to MySQLi.

I have made a file called db.php with the connection settings.

The file includes

<?php
$db = new mysqli('localhost','mysqlusername','mysqlpassword');
echo "<h1>Success database connection</h1>";
if($db->connect_errno > 0)
{
die('No connection [' . $db->connect_error . ']');
}
?>

I include the file with:

require_once "/location/db.php";    

after that i use:

 if($db->connect_error)
 {
   echo "Not connected, error: ".$db->connect_error;
 }  
 else
 {
   echo "Connected.";
 }

It echo's Connected so I assume my connection is good.

I have 3 PHP variables which I want to insert in my database table Code

I first echo the variables so I am sure they have content.

After I validated my connection is alright (returned Connected) and echoing the content of the variables I want to do the query with:

$sql = "INSERT INTO 'Code' (`Name`, `Code`, `Admin`)
VALUES ('$name', '$code', '$admin')"; 
echo $sql;//show query
// Performs the $sql query on the server to insert the values
if ($db->query($sql) === TRUE)
{
    echo 'User Created.';
}
else 
{
    echo 'Errorcreating : '. $db->error;
}

I get the message Errorcreating : No database selected

I have the echo $sql to show me the query.

If I copy the query directly in SQL it works like it should.

This is my first time on MySQLi so it's possible I made a very dumb mistake but I can't find it.

回答1:

Use this

$db = new mysqli('localhost','mysqlusername','mysqlpassword','database');

Also your escape character is wrong don't use single quotes around tablename use backtick operator

$sql = "INSERT INTO `Code` (`Name`, `Code`, `Admin`)VALUES ('$name', '$code', '$admin')"; 


回答2:

You did, in fact, not selected any database. You've connected to the DB server, where there may be hundreds of databases. you need to specify which one you're sending the queries to!

Your query is fine, and it works when you input it directly because when you do so you already specified the database to use.



回答3:

You haven't selected your database in the code. According to this page in php.net, there is a parameter in mysqli_connect or mysqli constructor which you enter your database name.

Here is is a simple example:

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');


回答4:

try this

<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>


标签: php mysqli