user3589409
user3589409

Reputation:

PHP: Can't find my database

I'm having problems connecting to my database

<?php

@mysqli_connect( "127.0.0.1", "root", "root" ) or die( "Cannot connect to the database!" );
@mysqli_select_db( "phpherexamen" ) or die( "Connected to the database, but there's nothing here!" );
session_start();

?>

This is the code I'm using to connect too my bd, but i always get the message:

Connected to the database, but there's nothing here!

My db looks like thisenter image description here

What am I not seeing? :)

Upvotes: 0

Views: 180

Answers (4)

Steini
Steini

Reputation: 2783

Wether you use the object oriented style:

$handle = @mysqli_connect( "127.0.0.1", "root", "root" ) or die( "Cannot connect to the database!" );
$handle->mysqli_select_db( "phpherexamen" ) or die( "Connected to the database, but there's nothing here!" );

or the procedural style:

$handle = @mysqli_connect( "127.0.0.1", "root", "root" ) or die( "Cannot connect to the database!" );
    @$mysqli_select_db($handle, "phpherexamen" ) or die( "Connected to the database, but there's nothing here!" );

but Mysqli requires an object to know which connection the mysql select db should apply to.

Sidenote: The old extension MySQL that was replaced by MySQLi supported to cache the last connection so you didnt need to specify the database handle but this is a great error-magnet if you have a website using multiple connections or want to fire a query while looping a result or similar thatswhy this only works with a valid handle or better said object which is alot more sane then the other, old method.

Upvotes: 0

ODaniel
ODaniel

Reputation: 595

Store the connection in a variable, and then pass that to the select_db command.

$db = mysqli_connect(...);
mysqli_select_db($db, 'phpherexamen');

Upvotes: 0

Insyte
Insyte

Reputation: 2236

With procedural style mysqli you need to pass mysqli_select_db an instance of mysqli

$mysqli = mysqli_connect("127.0.0.1", "root", "root");
mysqli_select_db($mysqli, "phpherexamen");

Upvotes: 0

Georgi Bilyukov
Georgi Bilyukov

Reputation: 627

You should use the result of mysqli_connect function as a second parameter of the mysql_select_db function.

$link = mysqli_connect( "127.0.0.1", "root", "root" )
if (!$link) {
    die("Cannot connect to the database!");
}

$db_selected = mysql_select_db('phpherexamen', $link);
if (!$db_selected) {
    die ("Connected to the database, but there's nothing here!");
}

Upvotes: 2

Related Questions