error: Database not selected
Asked Answered
S

3

7

I'm stuck with this issue: No database selected. I roll over the same problems posted here, but after hours of reading I can't figure out why the database is not selected. I created a database job and a table job. I run the script with WAMP server. Sorry about the "everyday question." Please help!

<?php

// load Smarty library
require('C:/wamp/www/smarty-3.1.21/libs/Smarty.class.php');

$servername = "localhost";
$dbname = "job";

// Create connection
$conn = mysqli_connect($servername, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$smarty = new Smarty;

$smarty->setTemplateDir('C:\wamp\www\app\templates');
$smarty->setCompileDir('C:\wamp\www\app\templates_c');
$smarty->setConfigDir('C:\wamp\www\app\configs');
$smarty->setCacheDir('C:\wamp\www\app\cache');


$rows = array();
$sql = "SELECT * FROM job";
$result = mysqli_query($conn, $sql);

if (!$result) {
    echo 'MySQL Error: ' . mysqli_error($conn);
    exit;
}

while ($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row;
    }

$smarty->assign('output', $rows);
$smarty->display('result.tpl');

mysqli_close($conn);

?>
Sands answered 31/5, 2015 at 17:4 Comment(4)
Is your Database Credentials right ?Bullnecked
Those aren't the right parameters to mysqli_connect. You have to pass host, username, password, and then database name.Vocalise
mysqli_connect require host then username, password and then db name. Please try to assign thatLoverly
Thanks a lot! I skipped the username and password becouse that type of connection worked in mysql, but i see now in mysqli i have to write it. It works now, so thank you guys again for the quick answers!Sands
V
12

Those aren't the right parameters to mysqli_connect. You have to pass host, username, password, and then database name. You are passing only the host and the database name, so you are not connecting correctly.

Vocalise answered 31/5, 2015 at 17:8 Comment(0)
B
6

You are missing some parameters in your mysqli_connect() function, here is how it's supposed to be:

$dbHost = '127.0.0.1';
$dbUser = 'username';
$dbPass = 'password';
$dbDb = 'database';
$conn = mysqli_connect($dbHost, $dbUser, $dbPass, $dbDb);
Bushranger answered 31/5, 2015 at 17:20 Comment(1)
the most complete, clear answer with working example.Bawdry
L
5

mysqli_connect() requires four parameter, which are:-

host name, user name, password, database name (optional).

So you need to provide all these parameters. If you don't, you can't connect and you will get errors.

Note:- database name is optional you can use mysqli_select_db() for selecting database further.

Loverly answered 31/5, 2015 at 17:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.