4

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.

BrokenCode
  • 951
  • 4
  • 19
  • 43

4 Answers4

6

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.

Czechnology
  • 14,832
  • 10
  • 62
  • 88
2

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

WDRust
  • 3,663
  • 1
  • 19
  • 23
1

The problem is here:

while($row = mysql_fetch_array( $result )) {

In your db.php you are connecting with the improved MySQL extension (mysqli).

But in your while loop you use the old MySQL extension.

Repox
  • 15,015
  • 8
  • 54
  • 79
1

It looks like you are connecting to the database using the mysqli functions, but your query is using a mysql function.

Try switching your query to the mysqli function:

$result = mysqli_query("SELECT * FROM users")
jeremysawesome
  • 7,033
  • 5
  • 33
  • 37
  • 2
    Thanks very much, it worked but I had to amend it to `$result = mysqli_query($dblink, "SELECT * FROM users")` – BrokenCode Feb 25 '12 at 20:35