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?
When opening the connection you can pass the database name as a 4th parameter:
$db = new mysqli('localhost','mysqlusername','mysqlpassword','database');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With