Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No database selected [duplicate]

Tags:

php

mysql

mysqli

I have created a 'db.php' file where I make a connection to my db:

$db_user = 'usprojus';
$db_pass = 'xxxxxx';
$db_host = 'localhost';
// Verbinden
$dblink = mysqli_connect($db_host, $db_user, $db_pass);
// Datenbank "myproject" auswaehlen
// Entspricht "USE myproject;"
$selected = mysqli_select_db($dblink, 'myproject');
if (!$selected) {
    die ('Cannot use DB : '.mysqli_error($dblink));
}
mysqli_set_charset($dblink, 'utf8');

In order to test that is working I am trying to get data from my 'users' table:

require_once('db.php'); 

// Get all the data from the "users" table
$result = mysql_query("SELECT * FROM users") 
or die(mysql_error());  


// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
    // Print out the contents of each row into a table
    echo 'user_id: '.$row['user_id'].'<br />';
    echo 'date_registered: '.$row['date_registered'].'<br />'; 
    echo 'last_login: '.$row['last_login'].'<br />';
    echo 'username: '.$row['username'].'<br />';
    echo 'email: '.$row['email'].'<br />';
    echo 'password: '.$row['password'].'<br />';
    echo 'photo: '.$row['photo'].'<br />';
    echo 'description: '.$row['description'].'<br />';
    echo 'notify: '.$row['notify'].'<br />';

}

But I get this error in the browser:

No database selected

For the life of me I cannot figure out where the problem lies.

Sorry, I know this is a newbie question, and it seems it has been posted here several times. But I could not figure it out.

Thank you for your time and patience.

like image 202
BrokenCode Avatar asked Dec 28 '22 05:12

BrokenCode


2 Answers

You're mixing up mysqli_ and mysql_ functions.

I.e. mysqli_connect, mysqli_select_db, mysqli_set_charset but then mysql_query and mysql_fetch_array in your second file.

Choose one.

like image 174
Czechnology Avatar answered Jan 08 '23 03:01

Czechnology


Perhaps you should use mysqli_query() (see php docs)

like image 42
WDRust Avatar answered Jan 08 '23 02:01

WDRust