Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "No database selected" error message when executing SQL via mysqli?

Tags:

php

mysqli

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');

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 echoes "Connected." so I assume my connection is good.

I have 3 PHP variables which I want to insert into my database table.

After I validated my connection is alright I want to do the query with:

$stmt = $mysqli->prepare("INSERT INTO Code (`Name`, `Code`, `Admin`) VALUES (?,?,?)");
$stmt->execute([
    $name,
    $code,
    $admin
]);

But I get the error:

No database selected

I verified the syntax and the same SQL works when executed in MySQL CLI. What did I do wrong when using mysqli?

like image 403
Sven van den Boogaart Avatar asked Oct 15 '25 13:10

Sven van den Boogaart


2 Answers

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

$db = new mysqli('localhost','mysqlusername','mysqlpassword','database');
like image 88
chandresh_cool Avatar answered Oct 17 '25 22:10

chandresh_cool


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.

like image 41
STT LCU Avatar answered Oct 17 '25 22:10

STT LCU