简体   繁体   中英

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 this 在此处输入图片说明

What am I not seeing? :)

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!");
}

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");

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM