Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

php - No database selected error message

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When opening the connection you can pass the database name as a 4th parameter:

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

Also, your escape character is wrong. Don't use single quotes around table names, use backtick operator instead

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...